The VS Code of video editing, built for agents.
TypeScript
Refactor project handling and update request parameters
konstantin-paulus9e8b209f04a7
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 416578a5..ed7bfe81 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -78,9 +78,9 @@ export const MAIN_CHANNELS = {} as const;/**- * A project folder under the projects root: a real npm package with a JSX- * entry. Its package.json is the project record: `projectId` is what the- * project is, `displayName` the human name, `main` the entry file.+ * A project folder, wherever it lives: a real npm package with a JSX entry.+ * Its package.json is the project record: `projectId` is what the project+ * is, `displayName` the human name, `main` the entry file.*/export type ProjectInfo = {/**@@ -222,7 +222,7 @@ export type MainRequestMap = {response: string | null;};[MAIN_CHANNELS.PROJECTS_LIST]: {- request: { root: string };+ request: { dirs: string[] };response: ProjectInfo[];};[MAIN_CHANNELS.PROJECTS_GET]: {@@ -234,7 +234,7 @@ export type MainRequestMap = {response: ProjectInfo;};[MAIN_CHANNELS.PROJECTS_RESOLVE]: {- request: { root: string; ref: string };+ request: { dir: string };response: ProjectInfo | null;};[MAIN_CHANNELS.PROJECTS_CREATE]: {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex a8d26773..a3b1f346 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -310,10 +310,10 @@ if (app.requestSingleInstanceLock()) {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_LIST, ({ root }) => listProjects(root));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ dirs }) => listProjects(dirs));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, ({ root, ref }) => resolveProject(root, ref));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ dir }) => resolveProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>createProject(root, displayName),);diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 8235238d..ae8ff3c0 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -389,78 +389,28 @@ 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. Reads only. */-export async function listProjects(root: string): Promise<ProjectInfo[]> {- const dirs = await childDirs(root);- const projects = await Promise.all(dirs.map(describe));- return projects.filter((project): project is ProjectInfo => project !== null);-}-/**- * Where an id was last seen, so opening the project the URL names usually- * costs one package.json read instead of a scan of the root. Never trusted- * without rereading the file: a stale entry (folder renamed behind our back,- * project deleted) just falls through to the scan.+ * The projects among `dirs`, in that order. A folder that is gone or holds+ * no entry is left out rather than reported: the app keeps its own list of+ * projects (see the web app's projects host), and this is how it reads the+ * list back off the disk. Reads only.*/-const dirsById = new Map<string, string>();--const cacheKey = (root: string, id: string): string => `${root}\n${id}`;--/** Drops every cached id that pointed at `dir` (it moved, or is gone). */-function forgetDir(dir: string): void {- for (const [key, cached] of dirsById) {- if (cached === dir) dirsById.delete(key);- }+export async function listProjects(dirs: string[]): Promise<ProjectInfo[]> {+ const projects = await Promise.all(dirs.map(describe));+ return projects.filter((project): project is ProjectInfo => project !== null);}/**- * The project `ref` names under `root`: an id first, then a folder name, so- * links made before ids existed still open. Whatever is found is left holding- * an id — this is where a folder that predates them gets one — and the caller- * can send the app to that id's URL.- *- * Ids live in a file the user can copy, so two folders can end up with the- * same one. Nothing here can tell which was meant, so it settles for being- * predictable: the cache answers first, so a project stays the one that was- * already open, and a cold scan is ordered by folder name.+ * 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+ * app to that id's URL. What the app calls when it opens a project; null+ * when `dir` holds none.*/-export async function resolveProject(root: string, ref: string): Promise<ProjectInfo | null> {- if (!ref) return null;-- const found = async (dir: string): Promise<ProjectInfo | null> => {- dirsById.set(cacheKey(root, await ensureProjectId(dir)), dir);- return describe(dir);- };-- const cached = dirsById.get(cacheKey(root, ref));- if (cached && recordedId(await readPackage(cached)) === ref) {- const project = await describe(cached);- if (project) return project;- }-- let dirs: string[];- try {- dirs = await childDirs(root);- } catch {- return null;- }- const ids = await Promise.all(dirs.map(async (dir) => recordedId(await readPackage(dir))));-- const byId = dirs[ids.indexOf(ref)];- if (byId) return found(byId);-- const byName = dirs.find((dir) => basename(dir) === ref);- return byName ? found(byName) : null;+export async function resolveProject(dir: string): Promise<ProjectInfo | null> {+ const project = await describe(dir);+ if (!project || project.id) return project;+ await ensureProjectId(dir);+ return describe(dir);}// ---------------------------------------------------------------------------@@ -841,7 +791,6 @@ async function renameFolder(dir: string, displayName: string): Promise<string> {// as soon as it hears where the project went.unwatchProject(dir);await rename(dir, target);- forgetDir(dir);return target;} catch {return dir;@@ -877,7 +826,6 @@ export async function deleteProject(dir: string): Promise<string> {const id = recordedId(await readPackage(dir));unwatchProject(dir);await shell.trashItem(dir);- forgetDir(dir);return id;}diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsxindex aea9019c..4b17cac2 100644--- a/apps/web/src/components/dashboard/home-view.tsx+++ b/apps/web/src/components/dashboard/home-view.tsx@@ -50,7 +50,7 @@ import {openProjectFolder,pickProjectFolder,projectKey,- projectsRoot,+ projectsRevision,type ProjectInfo,} from "@/projects";@@ -110,8 +110,10 @@ export function DashboardHomeView() {// screen behind text the user has typed.const placeholder = createFadingPlaceholder(() => prompt().length === 0);+ // The projects the app knows — created here, or opened from a folder —+ // refetched whenever that list changes.const [projects, { refetch: refetchProjects }] = createResource(- projectsRoot,+ projectsRevision,() => listProjects(),);// The model is shared with the chat panel and remembered across sessions;diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsxindex fae14c88..0713bdeb 100644--- a/apps/web/src/components/dashboard/projects-view.tsx+++ b/apps/web/src/components/dashboard/projects-view.tsx@@ -35,7 +35,7 @@ import {isDesktop,listProjects,projectKey,- projectsRoot,+ projectsRevision,type ProjectInfo,} from "@/projects";@@ -45,7 +45,7 @@ export function DashboardProjectsView() {const navigate = useNavigate();const [search, setSearch] = createSignal("");const [sort, setSort] = createSignal<ProjectSortOption>("last-viewed");- const [projects, { refetch: refetchProjects }] = createResource(projectsRoot, () => listProjects());+ const [projects, { refetch: refetchProjects }] = createResource(projectsRevision, () => listProjects());const [selectedProject, setSelectedProject] = createSignal<string | null>(null);const [creating, setCreating] = createSignal(false);const [pendingDelete, setPendingDelete] = createSignal<ProjectInfo | null>(null);diff --git a/apps/web/src/dapi/handlers/context.ts b/apps/web/src/dapi/handlers/context.tsindex ff5d2bb2..822b3a54 100644--- a/apps/web/src/dapi/handlers/context.ts+++ b/apps/web/src/dapi/handlers/context.ts@@ -13,7 +13,7 @@ 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 projects live under, which project folder the app has open, where its+ * folder new projects go in, which project folder the app has open, where its* playhead sits, which font families are actually registered in the world* drawing it. With no project open only the root is left to report.*/diff --git a/apps/web/src/lib/db.ts b/apps/web/src/lib/db.tsindex a96b2007..b75a0c86 100644--- a/apps/web/src/lib/db.ts+++ b/apps/web/src/lib/db.ts@@ -23,16 +23,11 @@ export function generateProjectName(): string {}/**- * What a root's path points at: a folder of project folders ('multi', the- * dashboard's kind), or one project folder that is itself the root ('single',- * how `dapi open <path>` registers a project living anywhere on disk).- */-export type ProjectRootKind = 'multi' | 'single';--/**- * A folder the user keeps projects in (desktop; see @/projects). A path- * rather than a handle: on desktop the main process does the reading, and it- * takes paths.+ * A folder new projects are created in (desktop; see @/projects). A path+ * rather than a handle: on desktop the main process does the creating, and+ * it takes paths. Creating is the folder's one job — nothing looks inside it.+ * The projects the app shows are the ones it has on record (`ProjectRecord`),+ * wherever they live.** Stored as a list because there will be several. The app works against one* at a time for now — the most recently used, so no separate "active" flag@@ -42,13 +37,25 @@ export interface ProjectRoot {id: string;path: string; // Absolute path of the folder.name: string;- kind: ProjectRootKind;createdAt: string;lastUsedAt: string;}-/** Rows written before kinds existed are what every root was then: 'multi'. */-const normalizeRoot = (root: ProjectRoot): ProjectRoot => ({ ...root, kind: root.kind ?? 'multi' });+/**+ * A project the app knows: one it created, or one it was asked to open — from+ * the folder picker, or `dapi open <path>`. The dashboard lists these and+ * nothing else; the disk is never searched for projects. Keyed by folder,+ * which is how main addresses a project. The id is a copy of what the+ * folder's package.json said last time — enough to find the folder a URL+ * names without reading every record's package.json — and the folder has the+ * final say (see `resolveProject` in @/projects).+ */+export interface ProjectRecord {+ dir: string; // Absolute path of the project folder.+ id: string; // package.json `projectId`; "" while the folder has none.+ createdAt: string; // When the app first put it on record.+ lastOpenedAt: string;+}/*** The bundle a project last mounted successfully, keyed by its id. Two jobs:@@ -72,6 +79,14 @@ export interface GlobalDBSchema extends idb.DBSchema {'by-last-used': string;};};+ projects: {+ value: ProjectRecord;+ key: string;+ indexes: {+ 'by-id': string;+ 'by-last-opened': string;+ };+ };bundles: {value: ProjectBundle;key: string;@@ -79,10 +94,10 @@ export interface GlobalDBSchema extends idb.DBSchema {}const DB_NAME = 'diffusion-studio-idb';-const DB_VERSION = 2;+const DB_VERSION = 3;const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {- upgrade(db) {+ async upgrade(db, oldVersion, _newVersion, tx) {if (!db.objectStoreNames.contains('roots')) {const store = db.createObjectStore('roots', { keyPath: 'id' });store.createIndex('by-path', 'path', { unique: true });@@ -91,60 +106,65 @@ const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {if (!db.objectStoreNames.contains('bundles')) {db.createObjectStore('bundles', { keyPath: 'projectId' });}+ if (!db.objectStoreNames.contains('projects')) {+ const store = db.createObjectStore('projects', { keyPath: 'dir' });+ store.createIndex('by-id', 'id');+ store.createIndex('by-last-opened', 'lastOpenedAt');+ }+ if (oldVersion > 0 && oldVersion < 3) {+ const roots = tx.objectStore('roots');+ const projects = tx.objectStore('projects');++ let cursor = await roots.openCursor();+ while (cursor) {+ const { kind, ...root } = cursor.value as ProjectRoot & { kind?: 'multi' | 'single' };+ if (kind === 'single') {+ await projects.put({ dir: root.path, id: '', createdAt: root.createdAt, lastOpenedAt: root.lastUsedAt });+ await cursor.delete();+ } else if (kind) {+ await cursor.update(root);+ }+ cursor = await cursor.continue();+ }+ }},});-// ----------------------------------------------------------------------------// Project roots-/** Last segment of a path, whichever separator it uses. */const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean).pop() ?? path;/**- * Records `path` as a projects root of the given kind, or marks the one- * already recorded for it as just used — which, for a 'multi' root, is what- * makes it the active one. The kind is the caller's to say: a path re-opened- * another way takes the new kind.+ * Records `path` as a projects root, or marks the one already recorded for+ * it as just used — which is what makes it the active one.*/-export async function rememberProjectRoot(path: string, kind: ProjectRootKind = 'multi'): Promise<ProjectRoot> {+export async function rememberProjectRoot(path: string): Promise<ProjectRoot> {const db = await dbPromise;const now = new Date().toISOString();const existing = await db.getFromIndex('roots', 'by-path', path);const root: ProjectRoot = existing- ? { ...normalizeRoot(existing), name: folderLabel(path), kind, lastUsedAt: now }- : { id: nanoid(), path, name: folderLabel(path), kind, createdAt: now, lastUsedAt: now };+ ? { ...existing, name: folderLabel(path), lastUsedAt: now }+ : { id: nanoid(), path, name: folderLabel(path), createdAt: now, lastUsedAt: now };await db.put('roots', root);return root;}-/** Every projects root — of `kind`, when given — most recently used first. */-export async function listProjectRoots(kind?: ProjectRootKind): Promise<ProjectRoot[]> {+/** Every projects root, most recently used first. */+export async function listProjectRoots(): Promise<ProjectRoot[]> {const db = await dbPromise;- const roots = (await db.getAllFromIndex('roots', 'by-last-used')).reverse().map(normalizeRoot);- return kind ? roots.filter((root) => root.kind === kind) : roots;+ return (await db.getAllFromIndex('roots', 'by-last-used')).reverse();}-/**- * The root the app is working against: the 'multi' root used last, or null- * when there is none. Single-project roots never qualify — making one active- * would point the dashboard (and "new project") into a project folder.- */+/** The root the app is working against: the one used last, or null when there is none. */export async function lastUsedProjectRoot(): Promise<ProjectRoot | null> {const db = await dbPromise;- let cursor = await db+ const cursor = await db.transaction('roots', 'readonly').store.index('by-last-used').openCursor(null, 'prev');-- while (cursor) {- const root = normalizeRoot(cursor.value);- if (root.kind === 'multi') return root;- cursor = await cursor.continue();- }- return null;+ return cursor?.value ?? null;}/** Forgets a projects root. The folder itself is left alone. */@@ -153,8 +173,65 @@ export async function forgetProjectRoot(id: string): Promise<void> {await db.delete('roots', id);}-// ----------------------------------------------------------------------------// Project bundles+/**+ * Puts the project in `dir` on record, or marks the one already recorded+ * there as just opened. `id` is what its package.json says now — the record+ * keeps a copy, so a folder that has since been given an id gets it here.+ */+export async function rememberProject(dir: string, id: string): Promise<ProjectRecord> {+ const db = await dbPromise;+ const now = new Date().toISOString();+ const existing = await db.get('projects', dir);++ const record: ProjectRecord = existing+ ? { ...existing, id, lastOpenedAt: now }+ : { dir, id, createdAt: now, lastOpenedAt: now };++ await db.put('projects', record);+ return record;+}++/** Every project on record, most recently opened first. */+export async function listProjectRecords(): Promise<ProjectRecord[]> {+ const db = await dbPromise;+ return (await db.getAllFromIndex('projects', 'by-last-opened')).reverse();+}++/**+ * The records `ref` could name: those whose id it is, then — for links made+ * before ids existed, and folders opened by name — those whose folder it+ * names. Most recently opened first within each, so a project that was just+ * open wins over a copy of it.+ */+export async function findProjectRecords(ref: string): Promise<ProjectRecord[]> {+ const records = await listProjectRecords();+ return [+ ...records.filter((record) => record.id === ref),+ ...records.filter((record) => record.id !== ref && folderLabel(record.dir) === ref),+ ];+}++/**+ * Re-keys the record for `from` to `to`, for a project whose folder moved+ * (renaming one moves its folder). 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;+}++/** Takes the project in `dir` off the record. The folder itself is left alone. */+export async function forgetProject(dir: string): Promise<void> {+ const db = await dbPromise;+ await db.delete('projects', dir);+}/** Records the bundle `projectId` just mounted, replacing the one before it. */export async function rememberProjectBundle(projectId: string, code: string): Promise<void> {diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.tsindex acb3c459..7e30a161 100644--- a/apps/web/src/projects/host.ts+++ b/apps/web/src/projects/host.ts@@ -2,33 +2,29 @@* 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/. */-// Renderer half of on-disk projects. Projects live as folders under a root-// (persisted) — a default one until the user picks another; each project's-// package.json is its record (`projectId`, `displayName`, `main`). The-// desktop main process scans, scaffolds, renames, copies, trashes, compiles,-// and watches them. Desktop only for now: without the bridge every call-// rejects and the root is null.-//-// A project is addressed by its folder — an absolute path, which is what main-// takes — and identified by its id, which is what the app's URLs carry and-// what survives the folder being renamed. `resolveProject` is the one bridge-// between the two; callers get the folder from the `ProjectInfo` it answers-// with (and the open project's from `@/context/project`).import { createSignal } from 'solid-js';import { MAIN_CHANNELS } from '@desktop/main-channels';import { mainBridge } from '@/lib/ipc';-import { lastUsedProjectRoot, listProjectRoots, rememberProjectRoot } from '@/lib/db';+import {+ findProjectRecords,+ forgetProject,+ lastUsedProjectRoot,+ listProjectRecords,+ moveProjectRecord,+ rememberProject,+ rememberProjectRoot,+} from '@/lib/db';import type { CompileResult, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';export type { CompileResult, ProjectInfo, SourceEdit, WriteResult };-// The roots live in the app's IndexedDB (see @/lib/db) as a list-// keyed by path. The app works against one of them — the one used last — but-// the store is already the list several roots will need, so growing into them-// is UI rather than a migration.+// The roots live in the app's IndexedDB (see @/lib/db) as a list keyed by+// path. The app works against one of them — the one used last — but the+// store is already the list several roots will need, so growing into them is+// UI rather than a migration.//// Reading a database is asynchronous, so the root starts null and arrives a// tick later. Every call here waits for it, leaving only the UI to tell "no@@ -37,23 +33,36 @@ export type { CompileResult, ProjectInfo, SourceEdit, WriteResult };const [projectsRoot, setProjectsRoot] = createSignal<string | null>(null);const [rootsReady, setRootsReady] = createSignal(false);-/** The projects root folder: null until one is picked, and until `rootsReady`. */+/** The folder new projects are created in: null until one is picked, and until `rootsReady`. */export { projectsRoot };/** Whether the roots have been read back from the database yet. */export { rootsReady };+// Bumped whenever the list of known projects changes — one created, opened,+// renamed, copied, or deleted — so a view listing them can refetch on it.+const [projectsRevision, setProjectsRevision] = createSignal(1);++/** Changes whenever the list `listProjects` answers with would; a source for `createResource`. */+export { projectsRevision };++export const isDesktop = (): boolean => !!window.desktop;+const ready = new Promise<void>((resolve) => {lastUsedProjectRoot().then((root) => setProjectsRoot(root?.path ?? null))- .catch((error) => console.error('[projects] could not read the projects roots', error))+ .catch((error) => console.error('[projects] could not read the projects database', error)).finally(() => {setRootsReady(true);resolve();});});-export const isDesktop = (): boolean => !!window.desktop;+/** Puts `project` on the list (or marks it just opened) and tells the views. */+async function remember(project: ProjectInfo): Promise<void> {+ await rememberProject(project.dir, project.id);+ setProjectsRevision((revision) => revision + 1);+}/** The projects root, waited for: null off the desktop and until one is picked. */export async function getProjectsRoot(): Promise<string | null> {@@ -104,41 +113,49 @@ export async function ensureProjectsRoot(): Promise<string | null> {return root;}+/**+ * The projects the app knows that are still on disk, most recently opened+ * first. A record whose folder is gone (moved, trashed by hand, on a volume+ * that is not mounted) is skipped, not forgotten: it may well come back.+ */export async function listProjects(): Promise<ProjectInfo[]> {await ready;- const root = projectsRoot();- if (!root || !isDesktop()) return [];- return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { root });+ if (!isDesktop()) return [];++ const records = await listProjectRecords();+ if (!records.length) return [];+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { dirs: records.map((record) => record.dir) });}-/** Creates a project folder under the root, named after `displayName`. */+/** Creates a project folder under the root, named after `displayName`, and puts it on the list. */export async function createProject(displayName: string): Promise<ProjectInfo> {await ready;const root = projectsRoot();if (!root) throw new Error('No projects folder selected.');- return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, displayName });++ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, displayName });+ await remember(project);+ return project;}/*** The project `ref` names: its id, or — for links made before ids existed,- * and folders opened by name — its folder name. The active root is searched- * first (and hands out ids, so the app can put one in the URL); on a miss,- * the single-project roots answer for projects living anywhere else on disk,- * matched by id or folder name, most recently used first.+ * and folders opened by name — its folder name. Only projects on the list+ * can be found; the records say which folders to look in, and the folders+ * say what they are now (one may have been renamed or replaced behind our+ * back, or be a folder that predates ids — in which case main gives it one+ * here, so the app can put an id in the URL).*/export async function resolveProject(ref: string): Promise<ProjectInfo | null> {await ready;if (!ref || !isDesktop()) return null;- const root = projectsRoot();- if (root) {- const found = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { root, ref });- if (found) return found;- }-- for (const single of await listProjectRoots('single')) {- const project = await getProject(single.path);- if (project && (project.id === ref || project.name === ref)) return project;+ for (const record of await findProjectRecords(ref)) {+ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir: record.dir });+ if (!project || (project.id !== ref && project.name !== ref)) continue;+ // Just opened, and holding an id the record may not have had yet.+ await rememberProject(project.dir, project.id);+ return project;}return null;}@@ -146,21 +163,16 @@ export async function resolveProject(ref: string): Promise<ProjectInfo | null> {/*** Opens the folder `dir` as a project, making it one first when it is not:* the folder is created if missing and, when nothing in it can be an entry,- * given an `index.tsx` holding an empty stage — and nothing else. Remembered- * as a single-project root unless it lives under the active root (where the- * ordinary resolution already finds it), so it stays reachable by name or id- * across relaunches. How `dapi open <path>` lands anywhere on disk.+ * given an `index.tsx` holding an empty stage — and nothing else. Put on the+ * list, so it stays reachable by name or id across relaunches. How+ * `dapi open <path>` lands anywhere on disk.*/export async function openProjectFolder(dir: string): Promise<ProjectInfo> {await ready;if (!isDesktop()) throw new Error('Opening a project folder requires the desktop app.');const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_INIT, { dir });-- const root = projectsRoot();- const underRoot = root !== null && project.dir.startsWith(root.replace(/\/+$/, '') + '/');- if (!underRoot) await rememberProjectRoot(project.dir, 'single');-+ await remember(project);return project;}@@ -173,23 +185,34 @@ export async function getProject(dir: string): Promise<ProjectInfo | null> {/*** Renames the project: `displayName` in the record, and the folder with it.* The folder moves, so the answer says where the project now lives — hold on- * to it. Its id has not changed, and neither has its URL.+ * to it. Its id has not changed, and neither has its URL; the list follows+ * the folder.*/export async function renameProject(dir: string, displayName: string): Promise<ProjectInfo> {if (!dir) throw new Error('No project folder.');- return mainBridge.call(MAIN_CHANNELS.PROJECTS_RENAME, { dir, displayName });++ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RENAME, { dir, displayName });+ await moveProjectRecord(dir, project.dir);+ await remember(project);+ return project;}-/** Copies the project in `dir` next to itself and returns the copy (a new id). */+/** Copies the project in `dir` next to itself and returns the copy (a new id), on the list. */export async function duplicateProject(dir: string): Promise<ProjectInfo> {if (!dir) throw new Error('No project folder.');- return mainBridge.call(MAIN_CHANNELS.PROJECTS_DUPLICATE, { dir });++ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_DUPLICATE, { dir });+ await remember(project);+ return project;}-/** Moves the project in `dir` to the trash. */+/** Moves the project in `dir` to the trash and takes it off the list. */export async function deleteProject(dir: string): Promise<void> {if (!dir) throw new Error('No project folder.');- return mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });++ await mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });+ await forgetProject(dir);+ setProjectsRevision((revision) => revision + 1);}/**@@ -232,7 +255,7 @@ export function writeProjectConfig(dir: string, config: unknown): Promise<void>* amount of waiting here is load-bearing.*/export function watchProject(dir: string, onChange: (paths: string[]) => void, debounceMs = 80): () => void {- if (!isDesktop()) return () => {};+ if (!isDesktop()) return () => { };let pending: ReturnType<typeof setTimeout> | undefined;let changed = new Set<string>();@@ -252,6 +275,6 @@ export function watchProject(dir: string, onChange: (paths: string[]) => void, dreturn () => {clearTimeout(pending);stop();- mainBridge.call(MAIN_CHANNELS.PROJECTS_UNWATCH, { dir }).catch(() => {});+ mainBridge.call(MAIN_CHANNELS.PROJECTS_UNWATCH, { dir }).catch(() => { });};}diff --git a/packages/dapi/src/tools/context.ts b/packages/dapi/src/tools/context.tsindex 4f19f65e..82bb450e 100644--- a/packages/dapi/src/tools/context.ts+++ b/packages/dapi/src/tools/context.ts@@ -28,10 +28,10 @@ export const context = defineTool({name: "context",title: "App context",description:- "Report the current app context: the application root folder (always reported), the folder of the project the app has open (null when none is), where its playhead sits in seconds, the registered font families, and where its `generate.*` declarations stand. Poll it to wait for generations without blocking.",+ "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, the registered font families, and where its `generate.*` declarations stand. Poll it to wait for generations without blocking.",input: z.object({}),output: z.object({- rootDir: z.string().nullable().describe("folder projects live under; null until one has been chosen"),+ rootDir: z.string().nullable().describe("folder new projects are created in; null until one has been chosen"),projectDir: z.string().nullable().describe("absolute path of the open project; null when none is open"),currentTime: z.number()