The VS Code of video editing, built for agents.
TypeScript
refactor: streamline project creation and saving process
konstantin-paulus9bc577c77170
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex e7aed12d..2aa83e0d 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -44,14 +44,13 @@ export const MAIN_CHANNELS = {FILE_WRITE_CLOSE: "file:write-close",FILE_WRITE_ABORT: "file:write-abort",LOGS_GET: "logs:get",- PROJECTS_PICK_ROOT: "projects:pick-root",PROJECTS_PICK_FOLDER: "projects:pick-folder",- PROJECTS_DEFAULT_ROOT: "projects:default-root",- PROJECTS_SCAN: "projects:scan",PROJECTS_GET: "projects:get",PROJECTS_INIT: "projects:init",PROJECTS_RESOLVE: "projects:resolve",PROJECTS_CREATE: "projects:create",+ PROJECTS_PICK_SAVE: "projects:pick-save",+ PROJECTS_SAVE: "projects:save",PROJECTS_RENAME: "projects:rename",PROJECTS_DUPLICATE: "projects:duplicate",PROJECTS_DELETE: "projects:delete",@@ -93,7 +92,7 @@ export type ProjectInfo = {* since — `PROJECTS_RESOLVE` is what gives one out.*/id: string;- /** Folder name. Renaming the project moves it, so it is not the identity. */+ /** Folder name. The user can move or rename it, so it is not the identity. */name: string;/** Human name from package.json `displayName` (falls back to the folder name). */displayName: string;@@ -105,6 +104,11 @@ export type ProjectInfo = {modifiedAt: string;/** birthtime of the folder, ISO string. */createdAt: string;+ /**+ * Whether the folder is a draft's: in the app's drafts folder, named after+ * the id, until the user saves it somewhere of their choosing.+ */+ draft: boolean;};export type CompileResult =@@ -221,24 +225,10 @@ export type MainRequestMap = {response: void;};[MAIN_CHANNELS.LOGS_GET]: { request: void; response: LogEntry[] };- [MAIN_CHANNELS.PROJECTS_PICK_ROOT]: {- request: void;- response: string | null;- };[MAIN_CHANNELS.PROJECTS_PICK_FOLDER]: {request: void;response: string | null;};- [MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT]: {- request: void;- response: string | null;- };- // Every project folder directly under `root`: what the app puts on its- // list when `root` is chosen as the projects root.- [MAIN_CHANNELS.PROJECTS_SCAN]: {- request: { root: string };- response: ProjectInfo[];- };[MAIN_CHANNELS.PROJECTS_GET]: {request: { dir: string };response: ProjectInfo | null;@@ -251,11 +241,19 @@ export type MainRequestMap = {request: { dir: string };response: ProjectInfo | null;};+ // A new project, as a draft called "Untitled" until it is saved.[MAIN_CHANNELS.PROJECTS_CREATE]: {- request: { root: string; displayName: string };+ request: void;+ response: ProjectInfo;+ };+ [MAIN_CHANNELS.PROJECTS_PICK_SAVE]: {+ request: { dir: string; displayName: string; startIn: string | null };+ response: string | null;+ };+ [MAIN_CHANNELS.PROJECTS_SAVE]: {+ request: { dir: string; target: string };response: ProjectInfo;};- // Renames the project: `displayName` in the record. The folder is left alone.[MAIN_CHANNELS.PROJECTS_RENAME]: {request: { dir: string; displayName: string };response: ProjectInfo;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 4354e0dc..41261aed 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -24,16 +24,15 @@ import { MAIN_CHANNELS } from "./main-channels";import {compileProject,createProject,- defaultRoot,deleteProject,duplicateProject,getProject,initProject,pickFolder,- pickRoot,+ pickSaveLocation,renameProject,resolveProject,- scanProjects,+ saveProject,unwatchAll,listEntries,realPathEntry,@@ -382,16 +381,15 @@ if (squirrelLaunch) {mainBridge.handle(MAIN_CHANNELS.CLI_STATUS, () => cliStatus());mainBridge.handle(MAIN_CHANNELS.CLI_INSTALL, () => installCli());mainBridge.handle(MAIN_CHANNELS.CLI_UNINSTALL, () => uninstallCli());- mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, () => pickFolder(mainWindow));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, () => defaultRoot(mainWindow));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_SCAN, ({ root }) => scanProjects(root));mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_INIT, ({ dir }) => initProject(mainWindow, dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ dir }) => resolveProject(dir));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>- createProject(root, displayName),+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, () => createProject());+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, displayName, startIn }) =>+ pickSaveLocation(mainWindow, dir, displayName, startIn),);+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_SAVE, ({ dir, target }) => saveProject(dir, target));mainBridge.handle(MAIN_CHANNELS.PROJECTS_RENAME, ({ dir, displayName }) => renameProject(dir, displayName));mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir).then(deleteProjectChats));diff --git a/apps/desktop/src/projects.drafts.test.ts b/apps/desktop/src/projects.drafts.test.tsnew file mode 100644index 00000000..bb56ee86--- /dev/null+++ b/apps/desktop/src/projects.drafts.test.ts@@ -0,0 +1,86 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// A new project is a draft: made without asking, in the app's own folder,+// named after its id — until it is saved, which moves it where the user said+// and names it after the folder they chose.++import { tmpdir } from "node:os";+import { mkdir, mkdtemp, readdir, readFile, rm } from "node:fs/promises";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++let userData = "";++vi.mock("electron", () => ({+ app: { isPackaged: false, getPath: (name: string) => (name === "userData" ? userData : tmpdir()) },+ dialog: {},+ shell: {},+ ipcMain: { on: () => { } },+}));++const { createProject, draftsRoot, duplicateProject, readManifest, saveProject, writeManifest } = await import("./projects");++let root: string;++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), "drafts-test-"));+ userData = join(root, "userData");+});++afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++describe("drafts", () => {+ it("creates a draft in the drafts folder, named after its id", async () => {+ const project = await createProject();+ expect(project.draft).toBe(true);+ expect(project.dir).toBe(join(draftsRoot(), project.id));+ expect(project.name).toBe(project.id);+ expect(project.displayName).toBe("Untitled");+ expect(project.entry).toBe("index.tsx");+ });++ it("duplicates a draft as a draft with an id of its own", async () => {+ const source = await createProject();+ const copy = await duplicateProject(source.dir);+ expect(copy.draft).toBe(true);+ expect(copy.id).not.toBe(source.id);+ expect(copy.dir).toBe(join(draftsRoot(), copy.id));+ });++ it("saves a draft by moving it and naming it after the folder", async () => {+ const draft = await createProject();+ const target = join(root, "Saved", "My Ad");++ const saved = await saveProject(draft.dir, target);+ expect(saved).toMatchObject({ id: draft.id, dir: target, name: "My Ad", displayName: "My Ad", draft: false });+ expect(await readdir(draftsRoot())).toEqual([]);+ const pkg = JSON.parse(await readFile(join(target, "package.json"), "utf8"));+ expect(pkg.projectId).toBe(draft.id);+ });++ it("lands a write asked for before the save in the saved folder", async () => {+ const draft = await createProject();+ const target = join(root, "My Ad");++ const manifest = { version: 1, folders: [], assets: [{ id: "a" }] };+ const writing = writeManifest(draft.dir, manifest);+ await saveProject(draft.dir, target);+ await writing;+ expect(await readManifest(target)).toEqual(manifest);+ expect(await readdir(draftsRoot())).toEqual([]);+ });++ it("refuses a folder that exists, and a project that is not a draft", async () => {+ const draft = await createProject();+ const taken = join(root, "taken");+ await mkdir(taken);+ await expect(saveProject(draft.dir, taken)).rejects.toThrow(/already exists/);++ const saved = await saveProject(draft.dir, join(root, "saved"));+ await expect(saveProject(saved.dir, join(root, "again"))).rejects.toThrow(/saved already/);+ });+});diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 53894f99..8f0def75 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -6,7 +6,7 @@ import { app, dialog, shell, type BrowserWindow } from "electron";import { execFile } from "node:child_process";import { createHash } from "node:crypto";import { watch, type FSWatcher } from "node:fs";-import { cp, mkdir, readdir, readFile, realpath, rm, stat } from "node:fs/promises";+import { cp, mkdir, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises";import { createRequire } from "node:module";import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { nanoid } from "nanoid";@@ -154,54 +154,112 @@ async function describe(dir: string): Promise<ProjectInfo | null> {entry,modifiedAt: file.mtime.toISOString(),createdAt: folder.birthtime.toISOString(),+ draft: isDraft(dir),};}export const getProject = (dir: string): Promise<ProjectInfo | null> => describe(dir);+// ---------------------------------------------------------------------------+// Drafts++// A new project starts as a draft: a folder the app makes without asking,+// in a place of its own, named after the id. Saving it (⌘S) is when the user+// says where it goes and what the folder is called — the folder moves there,+// and from then on it is an ordinary project.+/**- * The folder projects go in when the user has not picked one. `~/Movies` on- * macOS, `Videos` elsewhere — chosen because it is the one media folder the- * sync services leave alone: iCloud's "Desktop & Documents Folders" covers- * only those two, and OneDrive's Known Folder Move only Desktop, Documents,- * and Pictures. It also needs no macOS permission prompt, which Documents and- * Desktop do. Created on demand, so a user who never makes a project never- * gets the folder.- *- * Null when it turns out to be synced after all and the user would rather- * pick somewhere else — the caller falls back to `pickRoot`.+ * The folder drafts live in. Inside the app's own data, which nothing syncs —+ * neither iCloud nor OneDrive reaches `Application Support` or `AppData` —+ * and which needs no permission prompt. On Windows the Local AppData rather+ * than the Roaming one, which a roaming profile would carry, media and all,+ * from machine to machine.+ */+export function draftsRoot(): string {+ const local = process.platform === "win32" ? process.env.LOCALAPPDATA : undefined;+ const base = local ? join(local, basename(app.getPath("userData"))) : app.getPath("userData");+ return join(base, "Drafts");+}++/** Whether `dir` is a draft's folder: directly inside `draftsRoot`. */+function isDraft(dir: string): boolean {+ const parent = dirname(resolve(dir));+ const root = draftsRoot();+ return process.platform === "win32" ? parent.toLowerCase() === root.toLowerCase() : parent === root;+}++/**+ * Where the save picker starts when no project has been saved yet: a folder+ * under `~/Movies` on macOS, `Videos` elsewhere — the one media folder the+ * sync services leave alone (iCloud's "Desktop & Documents Folders" covers+ * only those two, OneDrive's Known Folder Move only Desktop, Documents, and+ * Pictures), and one that needs no macOS permission prompt. Created on+ * demand, so a user who never saves a project never gets the folder.*/-export async function defaultRoot(window: BrowserWindow | null): Promise<string | null> {+async function defaultSaveFolder(): Promise<string> {const dir = join(app.getPath("videos"), "Diffusion Studio");- if (!(await confirmCloudLocation(window, dir, "Choose another folder"))) return null;await mkdir(dir, { recursive: true });return dir;}-export async function pickRoot(window: BrowserWindow | null): Promise<string | null> {- const options: Electron.OpenDialogOptions = {- title: "Choose projects folder",- defaultPath: app.getPath("videos"),- properties: ["openDirectory", "createDirectory"],+/** Characters no folder name can hold on one platform or another. */+const UNSAFE_NAME = /[\\/:*?"<>|]+/g;++/** Why the draft in `dir` cannot be saved as `target`, or null when it can. */+async function saveProblem(dir: string, target: string): Promise<string | null> {+ if (await exists(target)) {+ return `"${basename(target)}" already exists in ${basename(dirname(target))}. Choose another name.`;+ }+ const inside = relative(resolve(dir), resolve(target));+ if (!inside.startsWith("..") && !isAbsolute(inside)) return "A project can't be saved inside itself.";+ if (isDraft(target)) return "Choose a folder outside the drafts folder.";+ return null;+}++/**+ * Asks where to save the draft in `dir`: the folder it will become, or null+ * when the user cancels. Starts in `startIn` — the parent of the last+ * project saved — with the project's name filled in. A name that is taken is+ * refused rather than replaced, and a synced folder is warned about; either+ * way the picker comes back, since the user came here to save.+ */+export async function pickSaveLocation(+ window: BrowserWindow | null,+ dir: string,+ displayName: string,+ startIn: string | null,+): Promise<string | null> {+ const start = startIn && (await stat(startIn).catch(() => null))?.isDirectory() ? startIn : await defaultSaveFolder();+ const name = displayName.replace(UNSAFE_NAME, "-").trim() || basename(dir);+ const options: Electron.SaveDialogOptions = {+ title: "Save project",+ buttonLabel: "Save",+ defaultPath: join(start, name),+ properties: ["createDirectory", "showOverwriteConfirmation"],};- // Declining a synced folder reopens the picker rather than dropping the- // user back to the dashboard: they came here to choose one.while (true) {- const { canceled, filePaths } = window- ? await dialog.showOpenDialog(window, options)- : await dialog.showOpenDialog(options);- if (canceled || !filePaths[0]) return null;- if (await confirmCloudLocation(window, filePaths[0], "Choose another folder")) {- return filePaths[0];+ const { canceled, filePath } = window+ ? await dialog.showSaveDialog(window, options)+ : await dialog.showSaveDialog(options);+ if (canceled || !filePath) return null;+ options.defaultPath = filePath;++ const problem = await saveProblem(dir, filePath);+ if (problem) {+ const message: Electron.MessageBoxOptions = { type: "warning", message: "Can't save here", detail: problem };+ if (window) await dialog.showMessageBox(window, message);+ else await dialog.showMessageBox(message);+ continue;}+ if (await confirmCloudLocation(window, filePath, "Choose another folder")) return filePath;}}/**- * A folder to open as a single project, wherever it lives. Unlike `pickRoot`- * this leaves the projects root alone, and it does not vet the location: the- * folder goes through `initProject`, which asks about a synced one there.+ * A folder to open as a single project, wherever it lives. It does not vet+ * the location: the folder goes through `initProject`, which asks about a+ * synced one there.*/export async function pickFolder(window: BrowserWindow | null): Promise<string | null> {const options: Electron.OpenDialogOptions = {@@ -382,26 +440,6 @@ async function confirmCloudLocation(return response === 1;}-/** Direct child folders of `root` that could hold a project, in a stable order. */-async function childDirs(root: string): Promise<string[]> {- const entries = await readdir(root, { withFileTypes: true });- return entries- .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")- .map((entry) => entry.name)- .sort()- .map((name) => join(root, name));-}--/**- * Every direct child folder of `root` that holds an entry file. The one- * search of the disk for projects there is: the app runs it when a projects- * root is chosen, to put the projects already in it on its list. Reads only.- */-export async function scanProjects(root: string): Promise<ProjectInfo[]> {- const projects = await Promise.all((await childDirs(root)).map(describe));- return projects.filter((project): project is ProjectInfo => project !== null);-}-/*** The project in `dir`, left holding an id — this is where a folder that* predates ids, or was made by hand, gets one — so the caller can send the@@ -418,17 +456,6 @@ export async function resolveProject(dir: string): Promise<ProjectInfo | null> {// ---------------------------------------------------------------------------// Scaffold-/** Folder-safe project name: "Golden River 15 Aug" -> "golden-river-15-aug". */-function folderName(name: string): string {- return (- name- .toLowerCase()- .replace(/[^a-z0-9._-]+/g, "-")- .replace(/^[-.]+|[-.]+$/g, "")- .slice(0, 64) || "project"- );-}-/** `base`, or `base-2`, `base-3`... when the folder is taken. */async function freeFolder(root: string, base: string): Promise<string> {let name = base;@@ -743,15 +770,21 @@ export async function initProject(window: BrowserWindow | null, dir: string): Prreturn project;}+/** What a new project is called until it is saved under a name of the user's. */+const DRAFT_NAME = "Untitled";+/**- * Creates a fresh project folder under `root`, named after `displayName`. A- * taken name is numbered rather than refused: the folder is a label, the id- * inside it is the project.+ * Creates a fresh project as a draft: a folder in `draftsRoot` named after+ * the id it is given here, so creating one asks nothing. `saveProject` is+ * what gives it a place and a name of the user's choosing.*/-export async function createProject(root: string, displayName: string): Promise<ProjectInfo> {- const dir = join(root, await freeFolder(root, folderName(displayName)));+export async function createProject(): Promise<ProjectInfo> {+ const id = nanoid();+ const dir = join(draftsRoot(), id);await mkdir(dir, { recursive: true });- await scaffold(dir, displayName);+ // The record first, so the scaffold keeps the id the folder is named after.+ await writePackage(dir, { ...packageJson(DRAFT_NAME, DRAFT_NAME), projectId: id });+ await scaffold(dir, DRAFT_NAME);const project = await describe(dir);if (!project) throw new Error("Failed to scaffold the project.");return project;@@ -771,13 +804,17 @@ export async function renameProject(dir: string, displayName: string): Promise<Preturn project;}-/** Copies the folder next to itself as `<name>-copy` (numbered when taken). */+/**+ * Copies the folder next to itself as `<name>-copy` (numbered when taken); a+ * draft's copy is a draft too, named after its own id.+ */export async function duplicateProject(dir: string): Promise<ProjectInfo> {const source = await describe(dir);if (!source) throw new Error("Not a project folder.");+ const id = nanoid();const root = dirname(dir);- const target = join(root, await freeFolder(root, `${source.name}-copy`));+ const target = source.draft ? join(root, id) : join(root, await freeFolder(root, `${source.name}-copy`));await cp(dir, target, { recursive: true, errorOnExist: true, force: false });// The record came along with everything else, id included, and two folders@@ -785,7 +822,7 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {const pkg = await readPackage(target);await writePackage(target, {...(pkg ?? packageJson(basename(target), source.displayName)),- projectId: nanoid(),+ projectId: id,displayName: `${source.displayName} (Copy)`,});const project = await describe(target);@@ -793,6 +830,33 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {return project;}+/**+ * Saves the draft in `dir` as `target`: moves its folder there and names the+ * project after it — the name the user typed in the save picker, which is+ * the draft's own unless they changed it. Writes still on their way into the+ * draft land first; whoever has it open lets go of the folder before asking+ * (see `ProjectProvider` in the web app), and opens it again where it went.+ */+export async function saveProject(dir: string, target: string): Promise<ProjectInfo> {+ if (!isDraft(dir)) throw new Error("This project is saved already.");+ if (!isAbsolute(target)) throw new Error(`The project folder must be an absolute path (got "${target}").`);+ const problem = await saveProblem(dir, target);+ if (problem) throw new Error(problem);++ await settleWrites(dir);+ unwatchProject(dir);+ await mkdir(dirname(target), { recursive: true });+ try {+ await rename(dir, target);+ } catch (error) {+ // Another volume: there is no moving a folder there, only copying it.+ if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;+ await cp(dir, target, { recursive: true, errorOnExist: true, force: false });+ await rm(dir, { recursive: true, force: true });+ }+ return renameProject(target, basename(target));+}+/*** Moves the folder to the trash; resolves with the id it had ("" for none), for what is kept outside it.* A folder that is already gone counts as deleted, so the project can still come off the list.@@ -923,13 +987,47 @@ export async function compileProject(dir: string): Promise<CompileResult> {* (see `noteContent`).*/export async function writeProject(dir: string, edits: SourceEdit[]): Promise<WriteResult> {+ const finish = startWrite(dir);try {return await applyEdits(sourceContext(dir), edits);} catch (error) {return { skipped: edits.map(editLabel), error: error instanceof Error ? error.message : String(error) };+ } finally {+ finish();}}+/**+ * Writes into a project that have not finished yet, by folder. Saving a draft+ * moves its folder, and waits these out first (see `settleWrites`): one that+ * lost the race would fail, or put a file back in the folder that just left.+ * A write starts before its first await, so one asked for before the save is+ * always among them.+ */+const writes = new Map<string, Set<Promise<void>>>();++/** Marks a write into `dir` as running; call what it returns when the write is done. */+function startWrite(dir: string): () => void {+ let release!: () => void;+ const done = new Promise<void>((resolve) => (release = resolve));+ const running = writes.get(dir) ?? new Set<Promise<void>>();+ writes.set(dir, running);+ running.add(done);++ return () => {+ release();+ running.delete(done);+ if (!running.size && writes.get(dir) === running) {+ writes.delete(dir);+ }+ };+}++/** Settles once every write into `dir` asked for so far has, however it went. */+async function settleWrites(dir: string): Promise<void> {+ await Promise.allSettled([...(writes.get(dir) ?? []), configWrites.get(dir)]);+}+// ---------------------------------------------------------------------------// Assets@@ -965,11 +1063,16 @@ export async function readManifest(dir: string): Promise<unknown> {* claimed first so the watcher does not hand it back as a change.*/export async function writeManifest(dir: string, manifest: unknown): Promise<void> {- const path = join(dir, MANIFEST_FILE);- const text = `# Diffusion Studio asset library. Edited by the app; hand edits are read on the next load.+ const finish = startWrite(dir);+ try {+ const path = join(dir, MANIFEST_FILE);+ const text = `# Diffusion Studio asset library. Edited by the app; hand edits are read on the next load.${stringifyYaml(manifest, { lineWidth: 0 })}`;- noteContent(path, text);- await writeFileAtomic(path, text);+ noteContent(path, text);+ await writeFileAtomic(path, text);+ } finally {+ finish();+ }}// ---------------------------------------------------------------------------diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsxindex 0fa73925..1d8bdcd0 100644--- a/apps/web/src/components/dashboard/home-view.tsx+++ b/apps/web/src/components/dashboard/home-view.tsx@@ -45,10 +45,8 @@ import {} from "@/agent-chat";import { projectRoute, useReturnHere } from "@/hooks/use-project-route";import { track } from "@/lib/analytics";-import { generateProjectName } from "@/lib/db";import {createProject,- ensureProjectsRoot,isDesktop,listProjects,openProjectFolder,@@ -194,10 +192,7 @@ export function DashboardHomeView() {if (current.kind === "project") return openProjectFromList(current.project);if (current.kind === "folder") return openProjectFolder(current.dir);- // Waits for the roots to come back from the database, and asks for one- // when there is none to wait for.- if (!(await ensureProjectsRoot())) return null;- return createProject(generateProjectName());+ return createProject();};const handleSubmit = async () => {diff --git a/apps/web/src/components/dashboard/projects-folder-bar.tsx b/apps/web/src/components/dashboard/projects-folder-bar.tsxdeleted file mode 100644index 31b18f82..00000000--- a/apps/web/src/components/dashboard/projects-folder-bar.tsx+++ /dev/null@@ -1,73 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { Show } from "solid-js";-import { toast } from "somoto";--import { Button } from "@/components/ui/button";-import { Icon } from "@/components/ui/icon";-import { revealPath } from "@/lib/shell";-import { isDesktop, pickProjectsRoot, projectsRoot } from "@/projects";--/**- * Footer bar of the projects view: shows the projects root and the actions on- * it. Desktop only — projects live on disk, so there is no root to show in the- * browser build (see @/projects).- */-export function DashboardProjectsFolderBar() {- const rootLabel = () => projectsRoot() ?? "No folder selected";- const hasRoot = () => !!projectsRoot();-- const handleChange = async () => {- try {- await pickProjectsRoot();- } catch (e) {- toast.error("Failed to choose projects folder", { description: (e as Error).message });- }- };-- const handleReveal = async () => {- const root = projectsRoot();- if (!root) return;-- try {- await revealPath(root);- } catch (e) {- toast.error("Failed to reveal projects folder", { description: (e as Error).message });- }- };-- return (- <Show when={isDesktop()}>- <div class="flex shrink-0 flex-col gap-3 border-t border-border px-4 py-3">- <div class="flex items-center gap-4">- <div class="flex min-w-0 flex-1 items-start gap-2">- <span class="relative size-4 shrink-0 text-muted-foreground">- <Icon- name="navigation.folder"- class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"- />- </span>- <div class="flex min-w-0 flex-1 flex-col justify-center gap-1">- <p class="h-4 text-xs text-foreground">Projects folder</p>- <p class="min-w-0 truncate text-xs text-muted-foreground">- {rootLabel()}- </p>- </div>- </div>- <div class="flex shrink-0 items-center gap-2">- <Show when={hasRoot()}>- <Button variant="ghost" class="text-muted-foreground" onClick={handleReveal}>- Reveal in finder- </Button>- </Show>- <Button variant="secondary" onClick={handleChange}>- {hasRoot() ? "Change..." : "Choose folder..."}- </Button>- </div>- </div>- </div>- </Show>- );-}diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsxindex 8841cf78..278f94ca 100644--- a/apps/web/src/components/dashboard/projects-view.tsx+++ b/apps/web/src/components/dashboard/projects-view.tsx@@ -26,7 +26,6 @@ import { DeleteProjectDialog } from "./delete-project-dialog";import { DashboardProjectCard } from "./project-card";import { parseTimestamp } from "./utils";import { DashboardSearchPanel } from "./search-bar";-import { DashboardProjectsFolderBar } from "./projects-folder-bar";import { projectRoute, useReturnHere } from "@/hooks/use-project-route";import { Icon } from "../ui/icon";import { track } from "@/lib/analytics";@@ -170,7 +169,6 @@ export function DashboardProjectsView() {)}</For></DashboardViewSection>- <DashboardProjectsFolderBar /><DeleteProjectDialogproject={pendingDelete()}diff --git a/apps/web/src/components/dashboard/settings-view.tsx b/apps/web/src/components/dashboard/settings-view.tsxindex 62723565..3134bc0e 100644--- a/apps/web/src/components/dashboard/settings-view.tsx+++ b/apps/web/src/components/dashboard/settings-view.tsx@@ -6,8 +6,6 @@ import { Match, Switch } from "solid-js";import { toast } from "somoto";import { Button } from "@/components/ui/button";-import { Icon } from "@/components/ui/icon";-import { pickProjectsRoot, projectsRoot } from "@/projects";import { usePermissionState, type PermissionState } from "@/hooks/use-permission";import {@@ -17,31 +15,6 @@ import {DashboardSurfaceSection,} from "./shared";-function DashboardProjectsFolderSection() {- const handleChange = async () => {- try {- await pickProjectsRoot();- } catch (e) {- toast.error("Failed to choose projects folder", { description: (e as Error).message });- }- };-- return (- <DashboardSurfaceSection title="Projects folder">- <DashboardInfoActionRow- title="Save projects to"- leading={<Icon name="navigation.folder" class="text-foreground" />}- description={projectsRoot() ?? "No folder selected"}- action={- <Button variant="secondary" onClick={handleChange}>- Change...- </Button>- }- />- </DashboardSurfaceSection>- );-}-type PermissionActionButtonProps = {state: PermissionState;pendingLabel: string;@@ -194,7 +167,6 @@ function DashboardPermissionsSection() {export function DashboardSettingsView() {return (<DashboardScrollView>- <DashboardProjectsFolderSection /><DashboardPermissionsSection /></DashboardScrollView>);diff --git a/apps/web/src/components/dashboard/shared.tsx b/apps/web/src/components/dashboard/shared.tsxindex 5bb827ff..7bef962b 100644--- a/apps/web/src/components/dashboard/shared.tsx+++ b/apps/web/src/components/dashboard/shared.tsx@@ -22,12 +22,11 @@ import { Separator } from "../ui/separator";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { toast } from "somoto";import { track } from "@/lib/analytics";-import { forgetProjectBundle, generateProjectName } from "@/lib/db";+import { forgetProjectBundle } from "@/lib/db";import {checkProject,createProject,deleteProject,- ensureProjectsRoot,forgetProject,isDesktop,type ProjectInfo,@@ -563,22 +562,16 @@ export function createBackgroundClickHandler(onCLick: () => void): JSX.EventHand}/**- * Creates a fresh, randomly named project under the projects root and puts- * it on the list. Null — with the reason already shown — when there is no- * desktop to create it on, and when the user is asked where to put it and- * declines to say. The one flow behind every "new project": the card on each- * view.+ * Creates a fresh project — an "Untitled" draft — and puts it on the list.+ * Null, with the reason already shown, when there is no desktop to create it+ * on. The one flow behind every "new project": the card on each view.*/export async function createNewProject(): Promise<ProjectInfo | null> {if (!isDesktop()) {toast.error("Projects on disk are only available in the desktop app");return null;}- // Waits for the roots to come back from the database, and asks for one- // when there is none to wait for.- if (!(await ensureProjectsRoot())) return null;-- const project = await createProject(generateProjectName());+ const project = await createProject();track("project_created");return project;}diff --git a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsxindex aa23c190..8f5fa061 100644--- a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx+++ b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx@@ -15,8 +15,8 @@ import {import { useLocation, useNavigate } from "@solidjs/router";import { For, Show, createMemo } from "solid-js";import { toast } from "somoto";-import { forgetProjectBundle, generateProjectName } from "@/lib/db";-import { createProject, deleteProject, duplicateProject, ensureProjectsRoot } from "@/projects";+import { forgetProjectBundle } from "@/lib/db";+import { createProject, deleteProject, duplicateProject } from "@/projects";import { AssetId, ChildOf, Name, Root, Scene, getAssetFile, getActiveEntity, sortByItemIndex } from "@diffusionstudio/runtime";import { assetName } from "@diffusionstudio/assets";import { useQuery, useWorld } from "@diffusionstudio/koota-solid";@@ -38,8 +38,7 @@ export function FileMenu() {const handleNewProject = async () => {try {- if (!(await ensureProjectsRoot())) return;- const created = await createProject(generateProjectName());+ const created = await createProject();navigate(projectRoute(created.id), { state: location.state });} catch (e) {toast.error("Failed to create project", {diff --git a/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsxnew file mode 100644index 00000000..fc8be9ad--- /dev/null+++ b/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsx@@ -0,0 +1,33 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { toast } from "somoto";+import {+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuShortcut,+} from "@/components/ui/dropdown-menu";+import { useProject } from "@/context/project";++/** What can be done with the project's folder. */+export function FolderMenu() {+ const project = useProject();++ const handleSaveFolder = async () => {+ try {+ await project.save();+ } catch (e) {+ toast.error("Failed to save project", { description: (e as Error).message });+ }+ };++ return (+ <DropdownMenuGroup>+ <DropdownMenuItem onSelect={handleSaveFolder} disabled={!project.draft()}>+ Save folder...+ <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>+ </DropdownMenuItem>+ </DropdownMenuGroup>+ );+}diff --git a/apps/web/src/components/sidebar-left/project-menu/index.tsx b/apps/web/src/components/sidebar-left/project-menu/index.tsxindex 97c1725a..956f1d31 100644--- a/apps/web/src/components/sidebar-left/project-menu/index.tsx+++ b/apps/web/src/components/sidebar-left/project-menu/index.tsx@@ -23,6 +23,7 @@ import { useEditorApi } from "@/dapi";import { desktopAppPlatformLabel, downloadDesktopApp } from "@/lib/desktop-app";import type { ProjectRouteState } from "@/hooks/use-project-route";import { FileMenu } from "./file-menu";+import { FolderMenu } from "./folder-menu";import { EditMenu } from "./edit-menu";import { ViewMenu } from "./view-menu";import { ToolMenu } from "./tool-menu";@@ -95,6 +96,15 @@ export function ProjectMenu() {</DropdownMenuPortal></DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Folder</DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent class="w-[196px]">+ <FolderMenu />+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+<DropdownMenuSub><DropdownMenuSubTrigger>Edit</DropdownMenuSubTrigger><DropdownMenuPortal>diff --git a/apps/web/src/components/sidebar-left/sidebar-left.tsx b/apps/web/src/components/sidebar-left/sidebar-left.tsxindex baddf7b4..11fdb634 100644--- a/apps/web/src/components/sidebar-left/sidebar-left.tsx+++ b/apps/web/src/components/sidebar-left/sidebar-left.tsx@@ -9,7 +9,9 @@ import { useEditorApi } from "@/dapi";import { createSignal, Show } from "solid-js";import { toast } from "somoto";import { Button } from "../ui/button";+import { badgeVariants } from "../ui/badge";import { Icon } from "../ui/icon";+import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";import { ProjectMenu } from "./project-menu";import { useProject } from "@/context/project";import { cx } from "@/lib/cva";@@ -85,10 +87,11 @@ export function EditorTitleBar(props: EditorTitleBarProps) {}><div- class="absolute left-1/2 top-1/2 flex max-w-[30%] -translate-x-1/2 -translate-y-1/2"+ class="absolute left-1/2 top-1/2 flex max-w-[30%] -translate-x-1/2 -translate-y-1/2 items-center gap-1.5"style="-webkit-app-region: no-drag;"><ProjectNameInput class="ml-0 w-auto min-w-8 max-w-full field-sizing-content text-center" />+ <DraftBadge /></div></WindowsTitleBar>)@@ -153,6 +156,41 @@ function ProjectNameInput(props: ProjectNameInputProps) {)}+/**+ * Marks a project that is still a draft: in the app's drafts folder until it+ * is saved somewhere. Clicking it saves, the same as ⌘S.+ */+function DraftBadge() {+ const project = useProject();++ const handleSave = async () => {+ try {+ await project.save();+ } catch (e) {+ toast.error("Failed to save project", { description: (e as Error).message });+ }+ };++ return (+ <Show when={project.draft()}>+ <Tooltip openDelay={600} placement="bottom">+ <TooltipTrigger+ as="button"+ type="button"+ onClick={handleSave}+ class={badgeVariants({+ variant: "secondary",+ class: "h-5 text-muted-foreground outline-none focus-ring hover:text-foreground",+ })}+ >+ Draft+ </TooltipTrigger>+ <TooltipContent shortcut={isWindowsDesktop() ? "Ctrl+S" : "⌘S"}>Save folder</TooltipContent>+ </Tooltip>+ </Show>+ );+}+type ProjectHeaderProps = {class?: string;}@@ -161,8 +199,9 @@ export function ProjectHeader(props: ProjectHeaderProps) {return (<div class={cx("h-12 shrink-0 flex items-center gap-1 pr-4 pl-2.5", props.class)}><ProjectMenu />- <div class="flex items-center w-full">- <ProjectNameInput />+ <div class="flex items-center w-full min-w-0 gap-1.5">+ <ProjectNameInput class="min-w-0" />+ <DraftBadge /></div></div>)diff --git a/apps/web/src/context/project.tsx b/apps/web/src/context/project.tsxindex 5f8cdc2a..ce75b18b 100644--- a/apps/web/src/context/project.tsx+++ b/apps/web/src/context/project.tsx@@ -7,25 +7,34 @@// world is under), the folder is where it lives, and the display name is what// the user calls it. Resolving the URL to a project happens once, in// ProjectPage; this is that answer, kept current as the project is renamed-// underneath the editor.+// underneath the editor, and as a draft is saved and its folder moves.-import { createContext, createMemo, createSignal, useContext, type Accessor, type JSX } from 'solid-js';+import { createContext, createMemo, createSignal, onCleanup, onMount, useContext, type Accessor, type JSX } from 'solid-js';+import { toast } from 'somoto';-import { refreshProject, renameProject } from '@/projects';+import { pickSaveLocation, refreshProject, renameProject, saveProject } from '@/projects';import type { ProjectInfo } from '@/projects';export type ProjectContextValue = {/** package.json `projectId`: what the project is, whatever it is called. */id: Accessor<string>;- /** Absolute project folder. */+ /** Absolute project folder; empty while a draft's folder is being moved. */dir: Accessor<string>;+ /** Whether the project is a draft: in the app's drafts folder until it is saved. */+ draft: Accessor<boolean>;/** package.json `displayName`: what the user calls it. */name: Accessor<string>;/** Renames the project — the record; the folder keeps its name. */rename: (displayName: string) => Promise<void>;/** Re-reads the record, for when something else wrote it. */refresh: () => Promise<void>;+ /**+ * Saves a draft: asks where, and moves its folder there. False when there+ * was nothing to save (not a draft, a save already running) or the user+ * cancelled.+ */+ save: () => Promise<boolean>;};const ProjectContext = createContext<ProjectContextValue>();@@ -35,11 +44,19 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Ele// arrives as a new provider rather than as a new value here.const [info, setInfo] = createSignal(props.project);+ // While a draft's folder moves nothing may hold it: the editor keys+ // everything that does — the watcher, the library, the writer, which+ // flushes what it still owes as it goes — on `dir`, so an empty one lets+ // go of the folder, and the new one attaches it all again where it went.+ const [moving, setMoving] = createSignal(false);+ let saving = false;+// Memos, not plain reads: a refresh that found nothing new must not look// like a change.const id = createMemo(() => info().id);- const dir = createMemo(() => info().dir);+ const dir = createMemo(() => (moving() ? '' : info().dir));const name = createMemo(() => info().displayName);+ const draft = createMemo(() => !!info().draft);const rename = async (displayName: string): Promise<void> => {setInfo(await renameProject(dir(), displayName));@@ -50,8 +67,47 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Eleif (next) setInfo(next);};+ const save = async (): Promise<boolean> => {+ if (!draft() || saving) return false;+ saving = true;+ try {+ const from = info().dir;+ // Asked before anything lets go: the user can still cancel, and the+ // editor keeps working behind the picker meanwhile.+ const target = await pickSaveLocation(from, info().displayName);+ if (!target) return false;++ setMoving(true);+ try {+ setInfo(await saveProject(from, target));+ } finally {+ setMoving(false);+ }+ return true;+ } finally {+ saving = false;+ }+ };++ /** ⌘S saves a draft. A saved project is written as it is edited, so there it does nothing. */+ const handleShortcut = async (event: KeyboardEvent) => {+ if (!(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) return;+ if (event.key.toLowerCase() !== 's') return;++ event.preventDefault();++ try {+ await save();+ } catch (error: unknown) {+ toast.error('Failed to save project', { description: (error as Error).message });+ }+ };++ onMount(() => window.addEventListener('keydown', handleShortcut));+ onCleanup(() => window.removeEventListener('keydown', handleShortcut));+return (- <ProjectContext.Provider value={{ id, dir, name, rename, refresh }}>+ <ProjectContext.Provider value={{ id, dir, draft, name, rename, refresh, save }}>{props.children}</ProjectContext.Provider>);diff --git a/apps/web/src/dapi/handlers/context.ts b/apps/web/src/dapi/handlers/context.tsindex e1f2a4e2..d00f64cd 100644--- a/apps/web/src/dapi/handlers/context.ts+++ b/apps/web/src/dapi/handlers/context.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { Computed, Fonts, FrameRate, getActiveEntity } from "@diffusionstudio/runtime";-import { getProjectsRoot } from "@/projects";+import { saveFolder } from "@/projects";import type { ToolHandler } from "../handler";@@ -11,13 +11,13 @@ import type { ToolHandler } from "../handler";* What the project's source cannot say. The JSX is the composition — its* scenes, what is selected, which scene is active, the work area are all in* the file, and a caller that wants them reads it. What is left over is which- * folder new projects go in, which project folder the app has open, where its+ * folder projects are saved to, which project folder the app has open, where its* playhead sits, and which font families are actually registered in the* world drawing it.* With no project open only the root is left to report.*/export const context: ToolHandler<"context"> = async (_, ctx) => {- const rootDir = await getProjectsRoot();+ const rootDir = saveFolder();const open = ctx.session();if (!open) return { rootDir, projectDir: null, currentTime: null, fontFamilies: [] };diff --git a/apps/web/src/lib/db.ts b/apps/web/src/lib/db.tsindex afc95485..653f6a67 100644--- a/apps/web/src/lib/db.ts+++ b/apps/web/src/lib/db.ts@@ -7,26 +7,9 @@ import type * as idb from 'idb';import type { ProjectInfo } from '@desktop/main-channels';-const adjectives = ["Golden", "Silent", "Fast", "Bright", "Dark", "Wild", "Calm"];-const nouns = ["River", "Mountain", "Dream", "Storm", "Sunset", "Forest", "Ocean"];--function getRandomElement<T>(arr: T[]): T {- return arr[Math.floor(Math.random() * arr.length)]!;-}--export function generateProjectName(): string {- const adj = getRandomElement(adjectives);- const noun = getRandomElement(nouns);- const now = new Date();- const day = now.getDate();- const month = now.toLocaleString("en-US", { month: "short" });- return `${adj} ${noun} ${day} ${month}`;-}-/**- * A project the app knows: one it created, one it was asked to open — from- * the folder picker, or `diffusion open <path>` — or one found in the projects- * root when that was chosen. The dashboard lists these and nothing else.+ * A project the app knows: one it created, or one it was asked to open — from+ * the folder picker, or `diffusion open <path>`. The dashboard lists these and nothing else.* Keyed by folder, which is how main addresses a project.*/export interface ProjectRecord extends ProjectInfo {@@ -93,16 +76,14 @@ const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean*/function placeholderRecord(dir: string, recordedAt: string, lastOpenedAt: string): ProjectRecord {const name = folderLabel(dir);- return { dir, id: '', name, displayName: name, entry: '', modifiedAt: lastOpenedAt, createdAt: recordedAt, recordedAt, lastOpenedAt, cover: null };+ return { dir, id: '', name, displayName: name, entry: '', modifiedAt: lastOpenedAt, createdAt: recordedAt, draft: false, recordedAt, lastOpenedAt, cover: null };}/*** Versions 1 and 2 kept a `roots` store: folders the dashboard scanned for* projects (`kind: 'multi'`), and single project folders registered on their* own (`kind: 'single'`). Version 3 does away with it. The single ones become- * project records; the multi ones are dropped — the projects root lives in- * localStorage now, and the projects the old one held come back on record- * when the user picks a root again (see `adoptProjectsRoot` in @/projects).+ * project records; the multi ones are dropped.*/async function retireRoots(db: idb.IDBPDatabase<GlobalDBSchema>, tx: UpgradeTransaction): Promise<void> {type LegacyRoot = { path: string; kind?: 'multi' | 'single'; createdAt: string; lastUsedAt: string };@@ -151,27 +132,6 @@ export async function updateProjectRecord(project: ProjectInfo): Promise<void> {await tx.done;}-/**- * Puts every project in `found` that is not on record yet on it, leaving the- * ones that are alone — they were opened when they were opened. Answers with- * how many were new. For the projects a freshly chosen root turns out to hold.- */-export async function addProjectRecords(found: ProjectInfo[]): Promise<number> {- const db = await dbPromise;- const now = new Date().toISOString();- const tx = db.transaction('projects', 'readwrite');- let added = 0;-- for (const project of found) {- if (await tx.store.getKey(project.dir)) continue;- await tx.store.put({ ...project, recordedAt: now, lastOpenedAt: now, cover: null });- added++;- }-- await tx.done;- return added;-}-/** Every project on record, most recently opened first. */export async function listProjectRecords(): Promise<ProjectRecord[]> {const db = await dbPromise;@@ -192,6 +152,23 @@ export async function findProjectRecords(ref: string): Promise<ProjectRecord[]>];}+/**+ * Re-keys the record for `from` to `to`, for a project whose folder moved (a+ * draft that was saved), cover and dates included. Nothing to do when `from`+ * is not on record.+ */+export async function moveProjectRecord(from: string, to: string): Promise<void> {+ if (from === to) return;+ const db = await dbPromise;+ const tx = db.transaction('projects', 'readwrite');+ const existing = await tx.store.get(from);+ if (existing) {+ await tx.store.delete(from);+ await tx.store.put({ ...existing, dir: to });+ }+ await tx.done;+}+/*** Records `cover` as the picture of the project in `dir`, replacing the one* before it. Nothing to do when the project is not on record: one deleteddiff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.tsindex 4e4b5bcf..ae603ea4 100644--- a/apps/web/src/projects/host.ts+++ b/apps/web/src/projects/host.ts@@ -8,10 +8,10 @@ import { createSignal } from 'solid-js';import { MAIN_CHANNELS } from '@desktop/main-channels';import { mainBridge } from '@/lib/ipc';import {- addProjectRecords,findProjectRecords,forgetProject as forgetProjectRecord,listProjectRecords,+ moveProjectRecord,rememberProject,updateProjectRecord,} from '@/lib/db';@@ -21,27 +21,25 @@ import type { ProjectRecord } from '@/lib/db';export type { CompileResult, ProjectInfo, ProjectRecord, SourceEdit, WriteResult };-// There is one projects root, so it is one localStorage value rather than a-// database row — read synchronously, so it is known from the first render.-// Unset for anyone who has never picked one, and for everyone upgrading from-// when the roots lived in the database: they get the default, or pick, the-// next time a project is created, and the projects the old root held come-// back with it (see `adoptProjectsRoot`).+// The folder the save picker starts in: the parent of the last project+// saved. One localStorage value, read synchronously. Kept under the key the+// projects root had, so the picker opens where an upgrading user's projects+// already are.-const ROOT_STORAGE_KEY = 'diffusion-studio:projects-root';+const SAVE_FOLDER_STORAGE_KEY = 'diffusion-studio:projects-root';-const storedRoot = (): string | null => {+const storedSaveFolder = (): string | null => {try {- return window.localStorage.getItem(ROOT_STORAGE_KEY);+ return window.localStorage.getItem(SAVE_FOLDER_STORAGE_KEY);} catch {return null;}};-const [projectsRoot, setProjectsRoot] = createSignal<string | null>(storedRoot());+const [saveFolder, setSaveFolder] = createSignal<string | null>(storedSaveFolder());-/** The folder new projects are created in: null until one is picked. */-export { projectsRoot };+/** The folder the save picker starts in: null until a project has been saved. */+export { saveFolder };// Bumped whenever the list of known projects changes — one created, opened,// renamed, copied, or deleted — so a view listing them can refetch on it.@@ -65,77 +63,26 @@ async function remember(project: ProjectInfo): Promise<void> {setProjectsRevision((revision) => revision + 1);}-/**- * Makes `root` the projects root, and puts the projects it already holds on- * the list — the ones that are not on it yet; the rest were opened when they- * were opened. This is the one time the disk is searched for projects, and- * what brings a user's projects back after an upgrade that forgot the root,- * or a reinstall: pick the folder again, and there they are.- */-async function adoptProjectsRoot(root: string): Promise<void> {+/** Makes `folder` where the next save picker starts. */+function storeSaveFolder(folder: string): void {try {- window.localStorage.setItem(ROOT_STORAGE_KEY, root);+ window.localStorage.setItem(SAVE_FOLDER_STORAGE_KEY, folder);} catch (error) {- console.warn('[projects] could not store the projects root', error);+ console.warn('[projects] could not store the save folder', error);}- setProjectsRoot(root);-- let found: ProjectInfo[] = [];- try {- found = await mainBridge.call(MAIN_CHANNELS.PROJECTS_SCAN, { root });- } catch (error) {- console.warn(`[projects] could not look for projects in ${root}`, error);- }- if (found.length && (await addProjectRecords(found))) {- setProjectsRevision((revision) => revision + 1);- }-}--/** The projects root: null off the desktop and until one is picked. */-export async function getProjectsRoot(): Promise<string | null> {- return projectsRoot();-}--/** Opens the native folder picker and adopts the chosen root. */-export async function pickProjectsRoot(): Promise<string | null> {- const root = await mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_ROOT, undefined);- if (!root) return null;-- await adoptProjectsRoot(root);- return root;+ setSaveFolder(folder);}/*** Opens the native folder picker for a folder to open as a single project.- * Unlike `pickProjectsRoot` it changes nothing on its own — hand the path to- * `openProjectFolder`, which is what makes the folder a project.+ * It changes nothing on its own — hand the path to `openProjectFolder`, which+ * is what makes the folder a project.*/export async function pickProjectFolder(): Promise<string | null> {if (!isDesktop()) return null;return mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, undefined);}-/**- * The root to work against, defaulted to when there is none. Null off the- * desktop, where there is no folder at all, and when the user is asked where- * to put projects and declines to say.- */-export async function ensureProjectsRoot(): Promise<string | null> {- if (!isDesktop()) return null;-- const current = projectsRoot();- if (current) return current;-- // Nothing picked yet: the default folder, so a first project costs a click- // rather than a trip through the folder picker. The picker is still there- // for anyone who wants to say — and for when the default will not do.- const root = await mainBridge.call(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, undefined);- if (!root) return pickProjectsRoot();-- await adoptProjectsRoot(root);- return root;-}-/*** The projects the app knows, most recently opened first, as their records* describe them — no folder is read. The dashboard shows this at launch, and@@ -181,13 +128,42 @@ export async function forgetProject(dir: string): Promise<void> {setProjectsRevision((revision) => revision + 1);}-/** Creates a project folder under the root, named after `displayName`, and puts it on the list. */-export async function createProject(displayName: string): Promise<ProjectInfo> {- const root = projectsRoot();- if (!root) throw new Error('No projects folder selected.');+/**+ * Creates a project and puts it on the list. It starts as a draft, called+ * "Untitled", in the app's own folder, so nothing is asked: where it lives and+ * what it is called are settled when it is saved (see `saveProject`).+ */+export async function createProject(): Promise<ProjectInfo> {+ if (!isDesktop()) throw new Error('Creating a project requires the desktop app.');++ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, undefined);+ await remember(project);+ return project;+}++/**+ * Asks where to save the draft in `dir`, starting where the last project was+ * saved: the folder it will become, or null when the user cancels. Moves+ * nothing yet.+ */+export function pickSaveLocation(dir: string, displayName: string): Promise<string | null> {+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_SAVE, { dir, displayName, startIn: saveFolder() });+}++/** The folder `path` is in. */+const parentOf = (path: string): string => path.replace(/[\\/]+[^\\/]*[\\/]*$/, '') || path;- const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, displayName });+/**+ * Moves the draft in `dir` to `target` (from `pickSaveLocation`), names it+ * after that folder, and answers with the project where it now lives. The+ * list follows the folder, and the next save picker starts beside it. Nothing+ * may hold the folder meanwhile — see `ProjectProvider`.+ */+export async function saveProject(dir: string, target: string): Promise<ProjectInfo> {+ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_SAVE, { dir, target });+ await moveProjectRecord(dir, project.dir);await remember(project);+ storeSaveFolder(parentOf(project.dir));return project;}diff --git a/docs/reference/tools/context.md b/docs/reference/tools/context.mdindex 8b0998f9..5b9085d8 100644--- a/docs/reference/tools/context.md+++ b/docs/reference/tools/context.md@@ -22,7 +22,7 @@ One JSON object:```ts{- rootDir: string | null; // absolute folder projects live under; null until one is picked+ rootDir: string | null; // absolute folder the last project was saved to; null until one has been savedprojectDir: string | null; // absolute open project folder — where the JSX being edited lives; null when none is opencurrentTime: number | null; // playhead in the active scene, in seconds; null if no scene is activefontFamilies: string[]; // families registered in the running world, valid as `fontFamily`@@ -31,7 +31,7 @@ One JSON object:With no project open (the app sits at the dashboard) the report is just `{ rootDir, projectDir: null }`: there is no playhead, no world, and no fonts to speak of. Open one with [`open`](./open.md).-`rootDir` is reported whether or not a project is open — it is where a caller with nothing open goes to create or find one.+`rootDir` is reported whether or not a project is open — it is where a caller with nothing open goes to find one. It is not where the app creates projects: a new project starts as a draft in the app's own folder, and moves when the user saves it (⌘S), which also makes its parent the new `rootDir`.`currentTime` is local to the active scene, the same origin a clip's `start` and `end` are placed against, and in the same unit.diff --git a/packages/dapi/src/tools/context.ts b/packages/dapi/src/tools/context.tsindex f680f624..0f8a3433 100644--- a/packages/dapi/src/tools/context.ts+++ b/packages/dapi/src/tools/context.ts@@ -14,10 +14,10 @@ export const context = defineTool({name: "context",title: "App context",description:- "Report the current app context: the folder new projects are created in (always reported), the folder of the project the app has open (null when none is), where its playhead sits in seconds, and the registered font families.",+ "Report the current app context: the folder projects are saved to (always reported), the folder of the project the app has open (null when none is), where its playhead sits in seconds, and the registered font families.",input: z.object({}),output: z.object({- rootDir: z.string().nullable().describe("folder new projects are created in; null until one has been chosen"),+ rootDir: z.string().nullable().describe("folder the last project was saved to; null until one has been saved"),projectDir: z.string().nullable().describe("absolute path of the open project; null when none is open"),currentTime: z.number()