The VS Code of video editing, built for agents.
TypeScript
Update project management features and dependencies
konstantin-paulus434b994881c7
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 5d228eca..13325a58 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -10,7 +10,7 @@"main": "dist/main.js","scripts": {"build:preload": "esbuild src/preload.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist/preload.js",- "build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist/main.js",+ "build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js","build:native": "node scripts/build-native.mjs","build": "npm run check && npm run build:main && npm run build:preload && npm run build:native","build:web": "npm --prefix ../web run build:desktop",@@ -27,13 +27,17 @@"@electron-forge/maker-dmg": "^7.11.1","@electron-forge/maker-zip": "^7.11.1","@electron-forge/publisher-github": "^7.11.1",+ "@types/babel__core": "^7.20.5","@types/node": "^24.10.1","electron": "^43.1.1",- "esbuild": "^0.28.1","typescript": "~5.9.3"},"dependencies": {+ "@babel/core": "^7.29.7",+ "@babel/preset-typescript": "^7.27.1","@diffusionstudio/cli": "*",+ "babel-preset-solid": "^1.9.12",+ "esbuild": "^0.28.1","update-electron-app": "^3.0.0"}}diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex bd31fdc9..eccd394e 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -38,14 +38,39 @@ export const MAIN_CHANNELS = {FILE_WRITE_ABORT: "file:write-abort",HEADLESS_GET_MODE: "headless:get-mode",LOGS_GET: "logs:get",+ PROJECTS_PICK_ROOT: "projects:pick-root",+ PROJECTS_LIST: "projects:list",+ PROJECTS_CREATE: "projects:create",+ PROJECTS_COMPILE: "projects:compile",+ PROJECTS_WATCH: "projects:watch",+ PROJECTS_UNWATCH: "projects:unwatch",// Main→Renderer eventsAUTH_CALLBACK: "auth:callback",CHECKOUT_CALLBACK: "checkout:callback",WINDOW_FULLSCREEN_CHANGE: "window:fullscreen-change",HEADLESS_MODE: "headless:mode",+ PROJECTS_CHANGED: "projects:changed",} as const;+/** A project folder under the projects root: a real npm package with a JSX entry. */+export type ProjectInfo = {+ /** Folder name, doubles as the project id. */+ name: string;+ /** Absolute path of the project folder. */+ dir: string;+ /** Entry file relative to `dir` (index.tsx, index.ts, index.jsx or index.js). */+ entry: string;+ /** mtime of the entry file, ISO string. */+ modifiedAt: string;+ /** birthtime of the folder, ISO string. */+ createdAt: string;+};++export type CompileResult =+ | { ok: true; code: string }+ | { ok: false; error: string };+export type MainChannel = (typeof MAIN_CHANNELS)[keyof typeof MAIN_CHANNELS];// Events fed by a `diffusion://` deep link. Main routes each link to exactly@@ -82,6 +107,15 @@ export type MainRequestMap = {};[MAIN_CHANNELS.HEADLESS_GET_MODE]: { request: void; response: boolean };[MAIN_CHANNELS.LOGS_GET]: { request: void; response: LogEntry[] };+ [MAIN_CHANNELS.PROJECTS_PICK_ROOT]: { request: void; response: string | null };+ [MAIN_CHANNELS.PROJECTS_LIST]: { request: { root: string }; response: ProjectInfo[] };+ [MAIN_CHANNELS.PROJECTS_CREATE]: {+ request: { root: string; name: string };+ response: ProjectInfo;+ };+ [MAIN_CHANNELS.PROJECTS_COMPILE]: { request: { dir: string }; response: CompileResult };+ [MAIN_CHANNELS.PROJECTS_WATCH]: { request: { dir: string }; response: void };+ [MAIN_CHANNELS.PROJECTS_UNWATCH]: { request: { dir: string }; response: void };};export type MainRequestChannel = keyof MainRequestMap;@@ -90,6 +124,8 @@ export type MainEventMap = {[MAIN_CHANNELS.CHECKOUT_CALLBACK]: { url: string };[MAIN_CHANNELS.WINDOW_FULLSCREEN_CHANGE]: { fullscreen: boolean };[MAIN_CHANNELS.HEADLESS_MODE]: { active: boolean };+ // A file inside a watched project folder changed (path relative to `dir`).+ [MAIN_CHANNELS.PROJECTS_CHANGED]: { dir: string; path: string };};export type MainEventChannel = keyof MainEventMap;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex e7b4f56b..de176131 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -13,6 +13,15 @@ import { trackInstall } from "./analytics";import { setupAppMenu } from "./menu";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";+import {+ compileProject,+ createProject,+ listProjects,+ pickRoot,+ unwatchAll,+ unwatchProject,+ watchProject,+} from "./projects";import type { DeepLinkChannel } from "./main-channels";import type { LogEntry } from "@diffusionstudio/cli/protocol";@@ -246,6 +255,14 @@ if (app.requestSingleInstanceLock()) {});mainBridge.handle(MAIN_CHANNELS.HEADLESS_GET_MODE, () => isHeadless());mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ root }) => listProjects(root));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, name }) => createProject(root, name));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) =>+ watchProject(BrowserWindow.fromWebContents(event.sender), dir),+ );+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => unwatchProject(dir));mainBridge.handle(MAIN_CHANNELS.FILE_TRANSFER, ({ selector, absolutePath }) =>setFileInputFiles(selector, absolutePath),);@@ -302,6 +319,7 @@ if (app.requestSingleInstanceLock()) {});app.on("before-quit", () => {+ unwatchAll();stopCliServer();});diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsnew file mode 100644index 00000000..85f20a7a--- /dev/null+++ b/apps/desktop/src/projects.ts@@ -0,0 +1,316 @@+/* 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/. */++// Projects on disk. A project is a plain folder that is a real npm package+// with a JSX entry file whose default export renders a <stage>. The user picks+// a root folder; every direct child folder holding an entry file is a project.+//+// Compilation bundles the entry with esbuild (which resolves node_modules for+// us) and runs project sources through babel-preset-solid's universal JSX+// transform, so the renderer can evaluate the resulting CommonJS bundle+// against its own solid-js instance and the koota-backed JSX host.++import { app, dialog, type BrowserWindow } from "electron";+import { watch, type FSWatcher } from "node:fs";+import { mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { join, relative, sep } from "node:path";++import type { TransformOptions } from "@babel/core";+import type { BuildOptions, Plugin } from "esbuild";++import { mainBridge } from "./main-manager";+import { MAIN_CHANNELS } from "./main-channels";+import type { CompileResult, ProjectInfo } from "./main-channels";++/** Entry points looked up in a project folder, in order of preference. */+export const ENTRY_FILES = ["index.tsx", "index.ts", "index.jsx", "index.js"];++/** The module compiled project code imports its JSX runtime from. */+const RUNTIME_MODULE = "@diffusionstudio/jsx";++/**+ * Imports left for the renderer to resolve against its own module instances+ * (one solid-js reactive graph, one JSX host).+ */+const EXTERNAL = ["solid-js", "solid-js/*", RUNTIME_MODULE];++const BUILD_OPTIONS: BuildOptions = {+ bundle: true,+ write: false,+ format: "cjs",+ platform: "browser",+ target: "chrome130",+ external: EXTERNAL,+ logLevel: "silent",+};++// esbuild and babel are kept external to the main bundle (esbuild ships a+// native binary). In development they resolve from the workspace; a packaged+// app has no node_modules of its own, so they load from the CLI's staged+// runtime at Contents/Resources/cli/node_modules (see scripts/stage-cli.mjs).+let stagedRequire: NodeJS.Require | undefined;++function load<T>(name: string): T {+ if (!app.isPackaged) return require(name) as T;+ stagedRequire ??= createRequire(join(process.resourcesPath, "cli", "package.json"));+ return stagedRequire(name) as T;+}++async function exists(path: string): Promise<boolean> {+ try {+ await stat(path);+ return true;+ } catch {+ return false;+ }+}++async function findEntry(dir: string): Promise<string | undefined> {+ for (const name of ENTRY_FILES) {+ if (await exists(join(dir, name))) return name;+ }+ return undefined;+}++const noEntryError = (): string => `No ${ENTRY_FILES.join(" / ")} found in this folder.`;++async function describe(dir: string, name: string): Promise<ProjectInfo | null> {+ const entry = await findEntry(dir);+ if (!entry) return null;+ const [folder, file] = await Promise.all([stat(dir), stat(join(dir, entry))]);+ return {+ name,+ dir,+ entry,+ modifiedAt: file.mtime.toISOString(),+ createdAt: folder.birthtime.toISOString(),+ };+}++export async function pickRoot(window: BrowserWindow | null): Promise<string | null> {+ const options: Electron.OpenDialogOptions = {+ title: "Choose projects folder",+ properties: ["openDirectory", "createDirectory"],+ };+ const { canceled, filePaths } = window+ ? await dialog.showOpenDialog(window, options)+ : await dialog.showOpenDialog(options);+ if (canceled || !filePaths[0]) return null;+ return filePaths[0];+}++/** Every direct child folder of `root` that holds an entry file. */+export async function listProjects(root: string): Promise<ProjectInfo[]> {+ const entries = await readdir(root, { withFileTypes: true });+ const projects = await Promise.all(+ entries+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")+ .map((entry) => describe(join(root, entry.name), entry.name)),+ );+ return projects.filter((project): project is ProjectInfo => project !== null);+}++// ---------------------------------------------------------------------------+// Scaffold++/** npm names: lowercase, url-safe, no leading dot or underscore, <= 214 chars. */+function packageName(name: string): string {+ const cleaned = name+ .toLowerCase()+ .replace(/[^a-z0-9._-]+/g, "-")+ .replace(/^[-_.]+|[-_.]+$/g, "")+ .slice(0, 214);+ return cleaned || "diffusion-project";+}++const packageJson = (name: string): string => `{+ "name": "${packageName(name)}",+ "private": true,+ "type": "module",+ "devDependencies": {+ "solid-js": "^1.9.10"+ }+}+`;++const TSCONFIG = `{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "preserve",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true+ },+ "include": ["**/*.ts", "**/*.tsx"]+}+`;++const STARTER = `export default function Scene() {+ return (+ <stage width={1920} height={1080}>+ <rect x={120} y={120} width={480} height={320} fill="#6366f1" />+ </stage>+ )+}+`;++// Types for the tags the editor renders. Owned by the app and re-synced on+// every open, so projects can't drift from the supported vocabulary.+const TYPES = `// Generated by Diffusion Studio. Types for the tags rendered on the canvas.+// Edits here are overwritten.++interface StageProps {+ x?: number+ y?: number+ width?: number+ height?: number+ children?: unknown+}++interface RectProps extends StageProps {+ fill?: string+}++declare namespace JSX {+ interface IntrinsicElements {+ stage: StageProps+ rect: RectProps+ }+}+`;++async function writeIfMissing(dir: string, name: string, content: string): Promise<void> {+ const path = join(dir, name);+ if (await exists(path)) return;+ await writeFile(path, content, "utf8");+}++async function writeIfChanged(dir: string, name: string, content: string): Promise<void> {+ const path = join(dir, name);+ const current = await readFile(path, "utf8").catch(() => undefined);+ if (current === content) return;+ await writeFile(path, content, "utf8");+}++/**+ * Turns `dir` into a starter TypeScript project: files the project owns are+ * written once, the generated types are kept in sync. Opening an up-to-date+ * project writes nothing.+ */+export async function scaffold(dir: string, name: string): Promise<void> {+ const entry = await findEntry(dir);+ // JavaScript projects are left alone.+ if (entry && !/\.tsx?$/.test(entry)) return;++ if (!entry) await writeIfMissing(dir, "index.tsx", STARTER);+ await writeIfMissing(dir, "package.json", packageJson(name));+ await writeIfMissing(dir, "tsconfig.json", TSCONFIG);+ await writeIfChanged(dir, "jsx.d.ts", TYPES);+}++/** Creates a fresh project folder under `root`. Fails if the folder exists. */+export async function createProject(root: string, name: string): Promise<ProjectInfo> {+ const dir = join(root, name);+ if (await exists(dir)) throw new Error(`"${name}" already exists in the projects folder.`);+ await mkdir(dir, { recursive: true });+ await scaffold(dir, name);+ const project = await describe(dir, name);+ if (!project) throw new Error("Failed to scaffold the project.");+ return project;+}++// ---------------------------------------------------------------------------+// Compile++type Babel = typeof import("@babel/core");+type Esbuild = typeof import("esbuild");++/** A preset however its package exposes it (CJS `module.exports` or an ESM default). */+function preset(name: string): unknown {+ const loaded = load<{ default?: unknown }>(name);+ return loaded.default ?? loaded;+}++const babelOptions = (filename: string): TransformOptions => ({+ filename,+ babelrc: false,+ configFile: false,+ presets: [+ [preset("babel-preset-solid"), { generate: "universal", moduleName: RUNTIME_MODULE }],+ [preset("@babel/preset-typescript"), { onlyRemoveTypeImports: true }],+ ],+});++/** Runs project sources (not node_modules) through Solid's universal JSX transform. */+function solidLoader(root: string): Plugin {+ const { transformAsync } = load<Babel>("@babel/core");+ return {+ name: "solid-universal",+ setup(build) {+ build.onLoad({ filter: /\.[jt]sx?$/ }, async (args) => {+ const name = relative(root, args.path);+ if (name.startsWith("..") || name.includes(`${sep}node_modules${sep}`) || name.startsWith(`node_modules${sep}`)) {+ return undefined;+ }+ const source = await readFile(args.path, "utf8");+ const result = await transformAsync(source, babelOptions(args.path));+ return { contents: result?.code ?? "", loader: "js" };+ });+ },+ };+}++export async function compileProject(dir: string): Promise<CompileResult> {+ const entry = await findEntry(dir);+ if (!entry) return { ok: false, error: noEntryError() };++ // Generated types may have drifted since the project was created.+ await scaffold(dir, dir.split(sep).pop() ?? "project");++ // esbuild resolves symlinks, so the loader has to match on real paths.+ const root = await realpath(dir);++ try {+ const { build } = load<Esbuild>("esbuild");+ const result = await build({+ ...BUILD_OPTIONS,+ entryPoints: [join(root, entry)],+ plugins: [solidLoader(root)],+ });+ return { ok: true, code: result.outputFiles![0]!.text };+ } catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) };+ }+}++// ---------------------------------------------------------------------------+// Watch++const watchers = new Map<string, FSWatcher>();++export function watchProject(window: BrowserWindow | null, dir: string): void {+ if (watchers.has(dir)) return;+ const watcher = watch(dir, { recursive: true }, (_event, filename) => {+ if (!filename) return;+ // Project-relative and `/`-separated; installs churn node_modules constantly.+ const path = filename.split(sep).join("/");+ if (path.startsWith("node_modules/") || path === "node_modules") return;+ mainBridge.emit(window, MAIN_CHANNELS.PROJECTS_CHANGED, { dir, path });+ });+ watcher.on("error", () => unwatchProject(dir));+ watchers.set(dir, watcher);+}++export function unwatchProject(dir: string): void {+ watchers.get(dir)?.close();+ watchers.delete(dir);+}++export function unwatchAll(): void {+ for (const dir of [...watchers.keys()]) unwatchProject(dir);+}diff --git a/apps/desktop/src/untyped-modules.d.ts b/apps/desktop/src/untyped-modules.d.tsnew file mode 100644index 00000000..736500ea--- /dev/null+++ b/apps/desktop/src/untyped-modules.d.ts@@ -0,0 +1,15 @@+/* 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/. */++// Babel presets ship no type declarations; they are only ever passed opaquely+// into @babel/core's `presets` option.+declare module "babel-preset-solid" {+ const preset: unknown;+ export default preset;+}++declare module "@babel/preset-typescript" {+ const preset: unknown;+ export default preset;+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex f66d8fb8..2a628d5f 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,6 +17,7 @@"@diffusionstudio/cli": "*","@diffusionstudio/jsx": "*","@diffusionstudio/koota-solid": "*",+ "@diffusionstudio/reconciler": "*","@diffusionstudio/runtime": "*","@kobalte/core": "^0.13.11","@sentry/solid": "^10.51.0",diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsxindex 41b47e2d..649f660c 100644--- a/apps/web/src/components/dashboard/projects-view.tsx+++ b/apps/web/src/components/dashboard/projects-view.tsx@@ -2,15 +2,7 @@* 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 {- deleteProject,- duplicateProject,- listRecentProjects,- setProjectName,- setProjectThumbnail,- DEFAULT_PROJECT_ID,- type ProjectEntry,-} from "@/components/engine/db";+import { generateProjectName, DEFAULT_PROJECT_ID } from "@/components/engine/db";import {ContextMenu,ContextMenuContent,@@ -19,6 +11,7 @@ import {ContextMenuSeparator,ContextMenuTrigger,} from "@/components/ui/context-menu";+import { Button } from "@/components/ui/button";import { TextField, TextFieldInput } from "@/components/ui/text-field";import { toast } from "somoto";import { For, Show, batch, createMemo, createResource, createSignal, onCleanup, onMount } from "solid-js";@@ -43,19 +36,48 @@ import { useProjectId } from "@/hooks/use-project-id";import { captureCanvasThumbnail } from "../engine/thumbnail";import { MAIN_CANVAS_ID } from "../canvas";import { Icon } from "../ui/icon";-import { nanoid } from "nanoid";import { track } from "@/lib/analytics";+import {+ createProject,+ isDesktop,+ listProjects,+ pickProjectsRoot,+ projectsRoot,+ type ProjectInfo,+} from "@/projects";import type { ProjectSortOption } from "./types";+// Projects live on disk under a user-picked root (see @/projects). Thumbnails,+// rename, duplicate and delete have no on-disk backing yet: the UI stays, the+// operations are no-ops until the desktop host grows them.+const thumbnails = new Map<string, Blob>();++async function setProjectThumbnail(name: string, blob: Blob): Promise<void> {+ thumbnails.set(name, blob);+}++async function setProjectName(_name: string, _newName: string): Promise<void> {+ // TODO: rename the project folder on disk.+}++async function duplicateProject(_name: string): Promise<ProjectInfo | null> {+ // TODO: copy the project folder on disk.+ return null;+}++async function deleteProject(_name: string): Promise<void> {+ // TODO: move the project folder to the trash.+}+export function DashboardProjectsView() {const projectId = useProjectId();const [, setParams] = useSearchParams();const [search, setSearch] = createSignal("");const [sort, setSort] = createSignal<ProjectSortOption>("last-viewed");- const [projects, { refetch: refetchProjects }] = createResource(() => listRecentProjects(32));- const [contextMenuProjectId, setContextMenuProjectId] = createSignal<string | null>(null);- const [renamingProjectId, setRenamingProjectId] = createSignal<string | null>(null);+ const [projects, { refetch: refetchProjects }] = createResource(projectsRoot, () => listProjects());+ const [contextMenuProject, setContextMenuProject] = createSignal<string | null>(null);+ const [renamingProject, setRenamingProject] = createSignal<string | null>(null);const [renameDraft, setRenameDraft] = createSignal("");const selectedSortOption = () =>@@ -66,10 +88,11 @@ export function DashboardProjectsView() {onMount(async () => {if (projectId() == DEFAULT_PROJECT_ID) return;- const canvas = document.getElementById(MAIN_CANVAS_ID) as HTMLCanvasElement;+ const canvas = document.getElementById(MAIN_CANVAS_ID) as HTMLCanvasElement | null;+ if (!canvas) return;const blob = await captureCanvasThumbnail(canvas);if (blob) {- setProjectThumbnail(projectId(), blob);+ await setProjectThumbnail(projectId(), blob);refetchProjects();};})@@ -96,27 +119,27 @@ export function DashboardProjectsView() {return entries;}- entries.sort((a, b) => parseTimestamp(b.lastAccessedAt) - parseTimestamp(a.lastAccessedAt));+ entries.sort((a, b) => parseTimestamp(b.modifiedAt) - parseTimestamp(a.modifiedAt));return entries;});- const openProject = (projectId: string) => {- if (renamingProjectId() === projectId) return;+ const openProject = (project: ProjectInfo) => {+ if (renamingProject() === project.name) return;track('project_opened');- setParams({ project: projectId, dashboard: undefined }, { replace: true });+ setParams({ project: project.name, dashboard: undefined }, { replace: true });};- const startRenaming = (project: ProjectEntry) => {+ const startRenaming = (project: ProjectInfo) => {batch(() => {setRenameDraft(project.name);- setRenamingProjectId(project.id);+ setRenamingProject(project.name);});};- const handleDelete = async (project: ProjectEntry) => {+ const handleDelete = async (project: ProjectInfo) => {try {- await deleteProject(project.id);+ await deleteProject(project.name);track('project_deleted');refetchProjects();} catch {@@ -124,9 +147,9 @@ export function DashboardProjectsView() {}};- const handleDuplicate = async (project: ProjectEntry) => {+ const handleDuplicate = async (project: ProjectInfo) => {try {- await duplicateProject(project.id);+ await duplicateProject(project.name);track('project_duplicated');refetchProjects();} catch {@@ -144,19 +167,19 @@ export function DashboardProjectsView() {const handleBlurRenameInput = () => {batch(() => {- setRenamingProjectId(null);+ setRenamingProject(null);setRenameDraft("");});refetchProjects();};- const handleKeyDownRenameInput = async (event: KeyboardEvent, projectId: string) => {+ const handleKeyDownRenameInput = async (event: KeyboardEvent, projectName: string) => {const input = event.currentTarget as HTMLInputElement;const trimmedName = renameDraft()?.trim() ?? "";if (event.key === "Escape") {refetchProjects();- setRenamingProjectId(null);+ setRenamingProject(null);setRenameDraft("");event.preventDefault();@@ -168,24 +191,44 @@ export function DashboardProjectsView() {event.preventDefault();event.stopPropagation();- if (trimmedName.length > 0 && projectId === renamingProjectId()) {- await setProjectName(projectId, trimmedName);+ if (trimmedName.length > 0 && projectName === renamingProject()) {+ await setProjectName(projectName, trimmedName);}refetchProjects();- setRenamingProjectId(null);+ setRenamingProject(null);setRenameDraft("");input.blur();};};- const handleCreateProject = () => {- track('project_created');- setParams({- project: nanoid(),- dashboard: undefined- }, { replace: true });+ const handleChooseRoot = async () => {+ if (!isDesktop()) {+ toast.error("Projects on disk are only available in the desktop app");+ return;+ }+ try {+ await pickProjectsRoot();+ } catch (e) {+ toast.error("Failed to choose projects folder", { description: (e as Error).message });+ }+ };++ const handleCreateProject = async () => {+ if (!projectsRoot()) {+ await handleChooseRoot();+ if (!projectsRoot()) return;+ }++ try {+ const project = await createProject(folderName(generateProjectName()));+ track('project_created');+ refetchProjects();+ openProject(project);+ } catch (e) {+ toast.error("Failed to create project", { description: (e as Error).message });+ }};return (@@ -198,27 +241,33 @@ export function DashboardProjectsView() {class="pb-4"title="Recent projects"controls={- <Select<(typeof SORT_OPTIONS)[number]>- options={SORT_OPTIONS}- value={selectedSortOption()}- onChange={(option) => option && setSort(option.id)}- optionValue="id"- optionTextValue="label"- itemComponent={(itemProps) => (- <SelectItem item={itemProps.item}>- {itemProps.item.rawValue.label}- </SelectItem>- )}- >- <SelectTrigger aria-label="Sort projects">- <SelectValue<(typeof SORT_OPTIONS)[number]>>- {(state) => state.selectedOption()?.label}- </SelectValue>- </SelectTrigger>- <SelectPortal>- <SelectContent />- </SelectPortal>- </Select>+ <>+ <Button variant="ghost" onClick={handleChooseRoot} title={projectsRoot() ?? undefined}>+ <Icon name="navigation.folder" class="mr-1 size-4" />+ {projectsRoot() ? folderLabel(projectsRoot()!) : "Choose projects folder"}+ </Button>+ <Select<(typeof SORT_OPTIONS)[number]>+ options={SORT_OPTIONS}+ value={selectedSortOption()}+ onChange={(option) => option && setSort(option.id)}+ optionValue="id"+ optionTextValue="label"+ itemComponent={(itemProps) => (+ <SelectItem item={itemProps.item}>+ {itemProps.item.rawValue.label}+ </SelectItem>+ )}+ >+ <SelectTrigger aria-label="Sort projects">+ <SelectValue<(typeof SORT_OPTIONS)[number]>>+ {(state) => state.selectedOption()?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectPortal>+ <SelectContent />+ </SelectPortal>+ </Select>+ </>}><DashboardCardButton onClick={handleCreateProject}>@@ -230,29 +279,29 @@ export function DashboardProjectsView() {</DashboardCardPreview><DashboardCardMeta title="New project" /></DashboardCardButton>- <For each={sortedProjects().filter(project => project.id !== DEFAULT_PROJECT_ID).slice(0, MAX_VISIBLE_PROJECTS)}>+ <For each={sortedProjects().slice(0, MAX_VISIBLE_PROJECTS)}>{(project) => (<ContextMenumodal={false}onOpenChange={(open) => {- setContextMenuProjectId((current) => {- if (open) return project.id;- return current === project.id ? null : current;+ setContextMenuProject((current) => {+ if (open) return project.name;+ return current === project.name ? null : current;});}}><ContextMenuTrigger as="div" class="contents"><DashboardCardButton- active={contextMenuProjectId() === project.id}- onClick={() => openProject(project.id)}+ active={contextMenuProject() === project.name}+ onClick={() => openProject(project)}><DashboardCardPreview>- <ProjectThumbnail thumbnail={project.thumbnail} />+ <ProjectThumbnail thumbnail={thumbnails.get(project.name)} /></DashboardCardPreview><div class="flex flex-col gap-1 px-2"><div class="relative h-4 w-full"><Show- when={renamingProjectId() === project.id}+ when={renamingProject() === project.name}fallback={<p class="min-w-0 truncate text-xs text-foreground">{project.name}@@ -267,7 +316,7 @@ export function DashboardProjectsView() {onInput={handleRenameInput}onFocus={handleFocusRenameInput}onBlur={handleBlurRenameInput}- onKeyDown={(e: KeyboardEvent) => handleKeyDownRenameInput(e, project.id)}+ onKeyDown={(e: KeyboardEvent) => handleKeyDownRenameInput(e, project.name)}placeholder="Project name"aria-label="Project name"class="absolute left-1/2 top-1/2 h-5 w-56 -translate-x-1/2 -translate-y-1/2 border border-ring bg-input px-1 py-0 ring-1 ring-inset ring-ring"@@ -276,14 +325,14 @@ export function DashboardProjectsView() {</Show></div><p class="min-w-0 truncate text-xs text-muted-foreground">- {formatEditedAt(project.lastAccessedAt)}+ {formatEditedAt(project.modifiedAt)}</p></div></DashboardCardButton></ContextMenuTrigger><ContextMenuPortal><ContextMenuContent class="w-45 gap-0">- <ContextMenuItem onSelect={() => openProject(project.id)}>+ <ContextMenuItem onSelect={() => openProject(project)}>Open</ContextMenuItem><ContextMenuSeparator class="my-2" />@@ -302,6 +351,11 @@ export function DashboardProjectsView() {</ContextMenu>)}</For>+ <Show when={projectsRoot() && !projects.loading && (projects()?.length ?? 0) === 0}>+ <p class="w-full px-2 pt-2 text-xs text-muted-foreground">+ No projects in this folder yet. A project is a folder with an index.tsx.+ </p>+ </Show></DashboardViewSection></DashboardSearchPanel>);@@ -331,20 +385,32 @@ function ProjectThumbnail(props: { thumbnail?: Blob }) {}const SORT_OPTIONS: Array<{ id: ProjectSortOption; label: string }> = [- { id: "last-viewed", label: "Last viewed" },+ { id: "last-viewed", label: "Last modified" },{ id: "alphabetical", label: "Alphabetical" },{ id: "date-created", label: "Date created" },];const MAX_VISIBLE_PROJECTS = 11;+/** 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, "") || "project";+}++function folderLabel(path: string): string {+ return path.split(/[\\/]/).filter(Boolean).pop() ?? path;+}+function parseTimestamp(value: string): number {const parsed = Date.parse(value);return Number.isNaN(parsed) ? 0 : parsed;}-function formatEditedAt(lastAccessedAt: string): string {- const timestamp = parseTimestamp(lastAccessedAt);+function formatEditedAt(modifiedAt: string): string {+ const timestamp = parseTimestamp(modifiedAt);if (!timestamp) return "Edited just now";const elapsedMs = Date.now() - timestamp;diff --git a/apps/web/src/components/engine/db/global-db.ts b/apps/web/src/components/engine/db/global-db.tsindex a2e82784..3acf0aa5 100644--- a/apps/web/src/components/engine/db/global-db.ts+++ b/apps/web/src/components/engine/db/global-db.ts@@ -164,7 +164,8 @@ export async function createProject(name?: string): Promise<ProjectEntry> {export async function getProjectName(projectId: string): Promise<string> {const project = projects.get(projectId);- if (!project) return generateProjectName();+ // Projects on disk are named by their folder (see @/projects).+ if (!project) return projectId === DEFAULT_PROJECT_ID ? generateProjectName() : projectId;return project.name;}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 52563f24..71cf1668 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,9 +15,9 @@ import {import { useSearchParams } from "@solidjs/router";import { getAllEntities } from "bitecs";import { For, Show, createMemo } from "solid-js";-import { nanoid } from "nanoid";import { toast } from "somoto";-import { deleteProject, duplicateProject, DEFAULT_PROJECT_ID } from "@/components/engine/db";+import { deleteProject, duplicateProject, DEFAULT_PROJECT_ID, generateProjectName } from "@/components/engine/db";+import { createProject, pickProjectsRoot, projectsRoot } from "@/projects";import { Not } from "bitecs";import { ChildOf, isScene, useQuery, loadAsset, changeAssetDirectory, removeAsset, getAssetFile } from "@/components/engine";import { useProjectId } from "@/hooks/use-project-id";@@ -31,11 +31,19 @@ export function FileMenu() {const projectId = useProjectId();const { world } = useEngine();- const handleNewProject = () => {- setParams({- project: nanoid(),- dashboard: undefined- }, { replace: true });+ const handleNewProject = async () => {+ try {+ if (!projectsRoot() && !(await pickProjectsRoot())) return;+ const project = await createProject(folderName(generateProjectName()));+ setParams({+ project: project.name,+ dashboard: undefined+ }, { replace: true });+ } catch (e) {+ toast.error("Failed to create project", {+ description: (e as Error).message,+ });+ }};const handleDuplicateProject = async () => {@@ -375,3 +383,11 @@ export function FileExportSpecificSceneMenu() {</DropdownMenuGroup>);}++/** 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, "") || "project";+}diff --git a/apps/web/src/hooks/use-project-id.ts b/apps/web/src/hooks/use-project-id.tsindex 6ce2ef6d..eed3634a 100644--- a/apps/web/src/hooks/use-project-id.ts+++ b/apps/web/src/hooks/use-project-id.ts@@ -7,22 +7,16 @@ import { useSearchParams } from "@solidjs/router";import { createMemo } from 'solid-js';import { DEFAULT_PROJECT_ID } from '@/components/engine/db';+// A project id is the name of a project folder under the projects root+// (see @/projects), so anything goes except path segments.+const PROJECT_ID = z.string().min(1).regex(/^(?!\.{1,2}$)[^/\\]+$/);+export function useProjectId() {const [params] = useSearchParams();-const projectId = createMemo(() => {- const { success, data } = z- .string()- .regex(/^[A-Za-z0-9_-]{21}$/)- .safeParse(params.project);-- if (!success) {- // when no project is set use a default project id- return DEFAULT_PROJECT_ID;- }-+ const { success, data } = PROJECT_ID.safeParse(params.project);+ if (!success) return DEFAULT_PROJECT_ID; // when no project is set use a default project idreturn data;});-return projectId;}diff --git a/apps/web/src/pages/home.tsx b/apps/web/src/pages/home.tsxindex f7671db0..44711b8f 100644--- a/apps/web/src/pages/home.tsx+++ b/apps/web/src/pages/home.tsx@@ -15,6 +15,8 @@ import { useSearchParams } from '@solidjs/router';import { ECSProvider } from '@/context/ecs';import { TimelineProvider } from '@/context/timeline';import { EngineProvider as KootaEngineProvider } from '@/engine';+import { ProjectLoader } from '@/projects';+import { DEFAULT_PROJECT_ID } from '@/components/engine/db';export function HomePage() {const projectId = useProjectId();@@ -27,6 +29,9 @@ export function HomePage() {<Show when={projectId()} keyed>{(id) => (<KootaEngineProvider projectId={id}>+ <Show when={id !== DEFAULT_PROJECT_ID}>+ <ProjectLoader name={id} />+ </Show><EngineProvider projectId={id}><EditorApiProvider><TimelineProvider>diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.tsnew file mode 100644index 00000000..6a701060--- /dev/null+++ b/apps/web/src/projects/host.ts@@ -0,0 +1,83 @@+/* 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/. */++// Renderer half of on-disk projects. Projects live as folders under a root+// the user picks once (persisted); the desktop main process scans, scaffolds,+// compiles, and watches them. Desktop only for now: without the bridge every+// call rejects and the root is null.++import { MAIN_CHANNELS } from '@desktop/main-channels';+import { mainBridge } from '@/lib/ipc';+import { store } from '@/init';+import { createStoredSignal } from '@/lib/store/signal';++import type { CompileResult, ProjectInfo } from '@desktop/main-channels';++export type { CompileResult, ProjectInfo };++const rootItem = store.define<string | null>('projects.root', null);+const [projectsRoot, setProjectsRoot] = createStoredSignal(rootItem);++/** The projects root folder, or null until the user picks one. */+export { projectsRoot };++export const isDesktop = (): boolean => !!window.desktop;++/** Opens the native folder picker and remembers the chosen root. */+export async function pickProjectsRoot(): Promise<string | null> {+ const root = await mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_ROOT, undefined);+ if (root) setProjectsRoot(root);+ return root;+}++export async function listProjects(): Promise<ProjectInfo[]> {+ const root = projectsRoot();+ if (!root || !isDesktop()) return [];+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { root });+}++/** Creates a new project folder under the root and returns it. */+export async function createProject(name: string): Promise<ProjectInfo> {+ const root = projectsRoot();+ if (!root) throw new Error('No projects folder selected.');+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, name });+}++/** Absolute folder of the project called `name` under the current root, or null. */+export function projectDir(name: string): string | null {+ const root = projectsRoot();+ if (!root) return null;+ // Names are folder names, never paths.+ if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) return null;+ const separator = root.includes('\\') ? '\\' : '/';+ return `${root}${separator}${name}`;+}++export function compileProject(dir: string): Promise<CompileResult> {+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_COMPILE, { dir });+}++/**+ * Watches a project folder and calls `onChange` (debounced) when a file+ * inside it changes. Returns the unwatch function.+ */+export function watchProject(dir: string, onChange: (path: string) => void, debounceMs = 80): () => void {+ if (!isDesktop()) return () => {};++ let pending: ReturnType<typeof setTimeout> | undefined;+ let last = '';+ const stop = mainBridge.handle(MAIN_CHANNELS.PROJECTS_CHANGED, (event) => {+ if (event.dir !== dir) return;+ last = event.path;+ clearTimeout(pending);+ pending = setTimeout(() => onChange(last), debounceMs);+ });+ void mainBridge.call(MAIN_CHANNELS.PROJECTS_WATCH, { dir });++ return () => {+ clearTimeout(pending);+ stop();+ void mainBridge.call(MAIN_CHANNELS.PROJECTS_UNWATCH, { dir }).catch(() => {});+ };+}diff --git a/apps/web/src/projects/index.ts b/apps/web/src/projects/index.tsnew file mode 100644index 00000000..d09e4898--- /dev/null+++ b/apps/web/src/projects/index.ts@@ -0,0 +1,6 @@+/* 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/. */++export * from './host';+export * from './loader';diff --git a/apps/web/src/projects/loader.tsx b/apps/web/src/projects/loader.tsxnew file mode 100644index 00000000..38cb679c--- /dev/null+++ b/apps/web/src/projects/loader.tsx@@ -0,0 +1,125 @@+/* 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 { createEffect, onCleanup } from 'solid-js';+import { toast } from 'somoto';+import { useWorld } from '@diffusionstudio/koota-solid';+import { mount } from '@diffusionstudio/reconciler';+import { ActiveScene, Camera, Position, RenderSurface, Size } from '@diffusionstudio/runtime';++import { compileProject, projectDir, watchProject } from './host';++import type { Mount } from '@diffusionstudio/reconciler';+import type { World } from 'koota';++export interface ProjectLoaderProps {+ /** Project folder name under the projects root. */+ name: string;+}++/**+ * Compiles the project folder, renders its JSX into the runtime world, and+ * re-renders on every change on disk. Renders nothing itself; mount it under+ * the koota EngineProvider.+ */+export function ProjectLoader(props: ProjectLoaderProps): null {+ const world = useWorld();++ createEffect(() => {+ const dir = projectDir(props.name);+ if (!dir) return;++ let mounted: Mount | undefined;+ let disposed = false;+ let generation = 0;+ // Only the first mount of a project frames the camera; reloads keep the view.+ let fitted = false;++ const unmount = (): void => {+ mounted?.dispose();+ mounted = undefined;+ };++ const load = async (): Promise<void> => {+ const current = ++generation;+ const result = await compileProject(dir);+ if (disposed || current !== generation) return;++ // A broken edit keeps the last good render on the canvas.+ if (!result.ok) {+ toast.error('Project failed to compile', { description: result.error });+ return;+ }++ // The old render goes first: there is only one active stage per world.+ unmount();+ try {+ mounted = mount(result.code, world);+ } catch (error) {+ toast.error('Project failed to render', { description: (error as Error).message });+ return;+ }++ if (!fitted) fitted = await fitCameraToStage(world);+ };++ void load();+ const unwatch = watchProject(dir, () => void load());++ onCleanup(() => {+ disposed = true;+ unwatch();+ unmount();+ });+ });++ return null;+}++const FIT_PADDING = 48;+const FIT_RETRIES = 30;++/**+ * Centers the active stage in the canvas. The canvas is sized by a resize+ * observer, so right after mount it may still be 0x0: retry a few frames.+ * Resolves true once the camera was set (or there is nothing to fit).+ */+function fitCameraToStage(world: World): Promise<boolean> {+ return new Promise((resolve) => {+ let attempts = 0;+ const attempt = (): void => {+ const stage = world.get(ActiveScene)?.entity;+ if (!stage) return resolve(true);++ const surface = world.get(RenderSurface);+ const canvas = surface?.canvas;+ const resolution = surface?.resolution || 1;+ const width = canvas ? canvas.width / resolution : 0;+ const height = canvas ? canvas.height / resolution : 0;++ if (!width || !height) {+ if (++attempts >= FIT_RETRIES) return resolve(false);+ requestAnimationFrame(attempt);+ return;+ }++ const size = stage.get(Size) ?? { width: 1, height: 1 };+ const position = stage.get(Position) ?? { x: 0, y: 0 };+ const scale = Math.min(+ (width - FIT_PADDING * 2) / Math.max(1, size.width),+ (height - FIT_PADDING * 2) / Math.max(1, size.height),+ );+ world.set(Camera, {+ a: scale,+ b: 0,+ c: 0,+ d: scale,+ e: (width - size.width * scale) / 2 - position.x * scale,+ f: (height - size.height * scale) / 2 - position.y * scale,+ });+ resolve(true);+ };+ attempt();+ });+}diff --git a/package-lock.json b/package-lock.jsonindex 856e00c9..80aadabc 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@diffusionstudio/editor",- "version": "0.132.0",+ "version": "0.132.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@diffusionstudio/editor",- "version": "0.132.0",+ "version": "0.132.1","hasInstallScript": true,"license": "MPL-2.0","workspaces": [@@ -19,7 +19,7 @@},"apps/cli": {"name": "@diffusionstudio/cli",- "version": "0.132.0",+ "version": "0.132.1","license": "MPL-2.0","dependencies": {"@babel/core": "^7.29.7",@@ -43,10 +43,14 @@},"apps/desktop": {"name": "@diffusionstudio/desktop",- "version": "0.132.0",+ "version": "0.132.1","license": "MPL-2.0","dependencies": {+ "@babel/core": "^7.29.7",+ "@babel/preset-typescript": "^7.27.1","@diffusionstudio/cli": "*",+ "babel-preset-solid": "^1.9.12",+ "esbuild": "^0.28.1","update-electron-app": "^3.0.0"},"devDependencies": {@@ -54,21 +58,22 @@"@electron-forge/maker-dmg": "^7.11.1","@electron-forge/maker-zip": "^7.11.1","@electron-forge/publisher-github": "^7.11.1",+ "@types/babel__core": "^7.20.5","@types/node": "^24.10.1","electron": "^43.1.1",- "esbuild": "^0.28.1","typescript": "~5.9.3"}},"apps/web": {"name": "@diffusionstudio/web",- "version": "0.132.0",+ "version": "0.132.1","license": "MPL-2.0","dependencies": {"@diffusionstudio/api-contract": "^0.1.0","@diffusionstudio/cli": "*","@diffusionstudio/jsx": "*","@diffusionstudio/koota-solid": "*",+ "@diffusionstudio/reconciler": "*","@diffusionstudio/runtime": "*","@kobalte/core": "^0.13.11","@sentry/solid": "^10.51.0",@@ -608,6 +613,10 @@"resolved": "packages/koota-solid","link": true},+ "node_modules/@diffusionstudio/reconciler": {+ "resolved": "packages/reconciler",+ "link": true+ },"node_modules/@diffusionstudio/runtime": {"resolved": "packages/runtime","link": true@@ -12347,6 +12356,23 @@"solid-js": "^1.9.0"}},+ "packages/reconciler": {+ "name": "@diffusionstudio/reconciler",+ "version": "0.1.0",+ "license": "MPL-2.0",+ "dependencies": {+ "@diffusionstudio/jsx": "*",+ "@diffusionstudio/runtime": "*",+ "koota": "^0.6.6"+ },+ "devDependencies": {+ "@webgpu/types": "^0.1.71",+ "typescript": "~5.9.3"+ },+ "peerDependencies": {+ "solid-js": "^1.9.0"+ }+ },"packages/runtime": {"name": "@diffusionstudio/runtime","version": "0.1.0",diff --git a/packages/reconciler/README.md b/packages/reconciler/README.mdnew file mode 100644index 00000000..046ae4b9--- /dev/null+++ b/packages/reconciler/README.md@@ -0,0 +1,21 @@+# @diffusionstudio/reconciler++Renders a project's JSX into a `@diffusionstudio/runtime` world. Sits between the compiler (which turns a project folder into a CommonJS bundle with `babel-preset-solid` in universal mode, `moduleName: "@diffusionstudio/jsx"`) and the runtime (which knows nothing about JSX):++```+project folder → compile (esbuild + babel) → code string → reconciler → runtime entities+```++- `evaluate(code)` runs the bundle against the app's own `solid-js` and `@diffusionstudio/jsx` (one reactive graph, one JSX runtime) and returns its default-exported component.+- `RuntimeDocument` implements `ProjectDocument` from `@diffusionstudio/jsx` over a runtime world: `<stage>` becomes a Scene entity, `<rect>` a rect entity, `fill` a solid paint child. It is the only place that knows how the runtime models nodes.+- `mount(code, world)` does both and returns a disposer that also destroys the rendered entities (Solid's universal render disposer only tears down the reactive graph).++```ts+import { mount } from '@diffusionstudio/reconciler';++const mounted = mount(compiled.code, world);+// ...later, e.g. on a file change:+mounted.dispose();+```++Supported today: `<stage>` and `<rect>` with `x`, `y`, `width`, `height`, and `fill` (rect only).diff --git a/packages/reconciler/package.json b/packages/reconciler/package.jsonnew file mode 100644index 00000000..51a739da--- /dev/null+++ b/packages/reconciler/package.json@@ -0,0 +1,32 @@+{+ "name": "@diffusionstudio/reconciler",+ "version": "0.1.0",+ "description": "Renders compiled project JSX (babel-preset-solid universal, via @diffusionstudio/jsx) into a @diffusionstudio/runtime world: evaluates the bundle and reconciles its element tree onto runtime entities.",+ "license": "MPL-2.0",+ "type": "module",+ "sideEffects": false,+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "check": "tsc --noEmit"+ },+ "keywords": [+ "reconciler",+ "solid-js",+ "jsx",+ "koota"+ ],+ "dependencies": {+ "@diffusionstudio/jsx": "*",+ "@diffusionstudio/runtime": "*",+ "koota": "^0.6.6"+ },+ "peerDependencies": {+ "solid-js": "^1.9.0"+ },+ "devDependencies": {+ "@webgpu/types": "^0.1.71",+ "typescript": "~5.9.3"+ }+}diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsnew file mode 100644index 00000000..9e872b99--- /dev/null+++ b/packages/reconciler/src/document.ts@@ -0,0 +1,224 @@+/* 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/. */++// The JSX host over the runtime world: Solid's universal renderer (via+// @diffusionstudio/jsx) writes project JSX straight into runtime entities, so+// a rendered project IS the composition, with no intermediate tree. This is+// the only file in the reconciler that knows how the runtime models nodes.+// Supported tags for now: <stage> (the composition root, a Scene) and <rect>,+// with x, y, width, height and fill (rect only).++import { Not } from 'koota';+import {+ appendChild,+ ChildOf,+ ClipsContent,+ Color,+ createEntity,+ Deleted,+ Geometry,+ GeometryType,+ getDocument,+ getParentEntity,+ ItemIndex,+ Name,+ Paint,+ PaintType,+ parseColor,+ Playback,+ Position,+ resizeEntity,+ Scene,+ sortByItemIndex,+ switchActiveScene,+} from '@diffusionstudio/runtime';++import type { Entity, World } from 'koota';+import type { ProjectDocument } from '@diffusionstudio/jsx';++const TAGS = ['stage', 'rect'] as const;+type Tag = (typeof TAGS)[number];++const isTag = (tag: string): tag is Tag => (TAGS as readonly string[]).includes(tag);++/**+ * A host node: an element's entity plus its tag. Entities are plain numbers,+ * which Solid's renderer would take for text, so nodes wrap them.+ */+export interface SceneNode {+ readonly entity: Entity;+ /** null for the mount root (the world's document root). */+ readonly tag: Tag | null;+}++const toNumber = (value: unknown): number | undefined => {+ if (value === undefined || value === null) return undefined;+ const number = Number(value);+ return Number.isFinite(number) ? number : undefined;+};++export class RuntimeDocument implements ProjectDocument<SceneNode> {+ /** The mount root: the world's document root entity. */+ public readonly stage: SceneNode;++ /** Elements this document created, by entity, so ordering only ever considers them (never paint sub-entities). */+ private readonly nodes = new Map<Entity, SceneNode>();++ public constructor(private readonly world: World) {+ this.stage = { entity: getDocument(world), tag: null };+ }++ public createElement(tag: string): SceneNode {+ if (!isTag(tag)) throw new Error(`<${tag}> is not supported yet (only <stage> and <rect>).`);++ const world = this.world;+ const entity = createEntity(world);+ entity.add(Geometry);+ entity.set(Geometry, { value: GeometryType.RECT });+ entity.add(Position);+ entity.set(Position, { x: 0, y: 0 });++ if (tag === 'stage') {+ // A scene is a RECT carrying Scene/ClipsContent/Playback plus a solid+ // fill; the same recipe the scene tool uses.+ entity.add(Scene);+ entity.add(ClipsContent);+ entity.add(Playback);+ entity.add(Name);+ entity.set(Name, { value: 'Stage' });+ resizeEntity(world, entity, { width: 1920, height: 1080 });+ this.setFill(entity, '#000000');+ } else {+ resizeEntity(world, entity, { width: 100, height: 100 });+ }++ const node: SceneNode = { entity, tag };+ this.nodes.set(entity, node);+ return node;+ }++ public createTextNode(): SceneNode {+ throw new Error('Text children are not supported.');+ }++ public replaceText(): void {}++ public isTextNode(): boolean {+ return false;+ }++ public setProperty(node: SceneNode, name: string, value: unknown): void {+ const { entity } = node;+ switch (name) {+ case 'x':+ case 'y': {+ entity.add(Position);+ entity.set(Position, { [name]: toNumber(value) ?? 0 });+ return;+ }+ case 'width':+ case 'height': {+ const size = toNumber(value);+ if (size === undefined) return;+ resizeEntity(this.world, entity, { [name]: size });+ return;+ }+ case 'fill': {+ if (node.tag !== 'rect') return;+ this.setFill(entity, value);+ return;+ }+ default:+ // children/ref and anything from a richer vocabulary: ignored, so+ // such a project still renders what this host understands.+ return;+ }+ }++ public insertNode(parent: SceneNode, node: SceneNode, anchor?: SceneNode): void {+ if (parent === this.stage) {+ if (node.tag !== 'stage') throw new Error('The root element must be <stage>.');+ // createEntity already parented the node to the document.+ switchActiveScene(this.world, node.entity);+ } else {+ if (parent.tag !== 'stage') throw new Error('<rect> cannot have children.');+ appendChild(this.world, node.entity, parent.entity);+ }+ this.reorder(parent, node, anchor);+ }++ public removeNode(_parent: SceneNode, node: SceneNode): void {+ this.nodes.delete(node.entity);+ // ChildOf auto-destroys orphans, so paints and children go with it.+ node.entity.destroy();+ }++ /**+ * Destroys everything this document rendered. Solid's universal render+ * disposer only tears down the reactive graph, never the host nodes.+ */+ public dispose(): void {+ for (const node of this.children(this.stage)) this.removeNode(this.stage, node);+ this.nodes.clear();+ }++ public getParentNode(node: SceneNode): SceneNode | undefined {+ const parent = getParentEntity(node.entity);+ if (parent === null) return undefined;+ return parent === this.stage.entity ? this.stage : this.nodes.get(parent);+ }++ public getFirstChild(node: SceneNode): SceneNode | undefined {+ return this.children(node)[0];+ }++ public getNextSibling(node: SceneNode): SceneNode | undefined {+ const parent = this.getParentNode(node);+ if (!parent) return undefined;+ const siblings = this.children(parent);+ return siblings[siblings.indexOf(node) + 1];+ }++ /** Element children of `parent` in draw order. */+ private children(parent: SceneNode): SceneNode[] {+ return [...this.world.query(ChildOf(parent.entity), Not(Deleted))]+ .sort(sortByItemIndex)+ .map((entity) => this.nodes.get(entity))+ .filter((node): node is SceneNode => node !== undefined);+ }++ /** Places `node` before `anchor` (or last) by rewriting sibling ItemIndex. */+ private reorder(parent: SceneNode, node: SceneNode, anchor?: SceneNode): void {+ const siblings = this.children(parent).filter((sibling) => sibling !== node);+ const at = anchor ? siblings.indexOf(anchor) : -1;+ if (at === -1) siblings.push(node);+ else siblings.splice(at, 0, node);+ for (const [index, sibling] of siblings.entries()) {+ sibling.entity.add(ItemIndex);+ sibling.entity.set(ItemIndex, { value: index });+ }+ }++ private setFill(entity: Entity, value: unknown): void {+ const color = typeof value === 'string' ? parseColor(value) : null;+ const paint = this.world.queryFirst(ChildOf(entity), Paint);++ if (color === null) {+ paint?.destroy();+ return;+ }++ if (paint) {+ paint.set(Color, { value: color });+ return;+ }++ const fill = createEntity(this.world);+ fill.add(Paint);+ fill.set(Paint, { value: PaintType.SOLID });+ fill.add(Color);+ fill.set(Color, { value: color });+ appendChild(this.world, fill, entity);+ }+}diff --git a/packages/reconciler/src/evaluate.ts b/packages/reconciler/src/evaluate.tsnew file mode 100644index 00000000..0b1193b2--- /dev/null+++ b/packages/reconciler/src/evaluate.ts@@ -0,0 +1,35 @@+/* 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 * as solid from 'solid-js';+import * as solidStore from 'solid-js/store';+import * as jsx from '@diffusionstudio/jsx';++// What the desktop compile step marks external is what is handed out here,+// so a project shares the app's solid-js instance (one reactive graph) and+// its JSX runtime.+const MODULES: Record<string, unknown> = {+ 'solid-js': solid,+ 'solid-js/store': solidStore,+ '@diffusionstudio/jsx': jsx,+};++/** Evaluates a compiled CommonJS bundle and returns its default export. */+export function evaluate(code: string): () => unknown {+ const module = { exports: {} as { default?: unknown } };++ const require = (id: string): unknown => {+ const resolved = MODULES[id];+ if (!resolved) throw new Error(`Cannot import "${id}" — only solid-js and @diffusionstudio/jsx are available.`);+ return resolved;+ };++ new Function('require', 'module', 'exports', code)(require, module, module.exports);++ const component = module.exports.default;+ if (typeof component !== 'function') {+ throw new Error('The entry file must export a component as default.');+ }+ return component as () => unknown;+}diff --git a/packages/reconciler/src/index.ts b/packages/reconciler/src/index.tsnew file mode 100644index 00000000..7c7ef61e--- /dev/null+++ b/packages/reconciler/src/index.ts@@ -0,0 +1,7 @@+/* 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/. */++export { RuntimeDocument, type SceneNode } from './document';+export { evaluate } from './evaluate';+export { mount, type Mount } from './mount';diff --git a/packages/reconciler/src/mount.ts b/packages/reconciler/src/mount.tsnew file mode 100644index 00000000..12a00504--- /dev/null+++ b/packages/reconciler/src/mount.ts@@ -0,0 +1,42 @@+/* 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 { renderProject } from '@diffusionstudio/jsx';++import { RuntimeDocument } from './document';+import { evaluate } from './evaluate';++import type { World } from 'koota';++export interface Mount {+ /** Tears down the reactive graph and every entity the project rendered. */+ dispose(): void;+}++/**+ * Renders a compiled project bundle into `world`. Throws if the bundle does+ * not evaluate or its root is not a <stage>; nothing is left behind in the+ * world when it throws.+ */+export function mount(code: string, world: World): Mount {+ const component = evaluate(code);+ const document = new RuntimeDocument(world);++ let dispose: () => void;+ try {+ dispose = renderProject(component, document);+ } catch (error) {+ document.dispose();+ throw error;+ }++ return {+ dispose() {+ // Solid's universal render disposer only drops the reactive graph;+ // the document owns the entities.+ dispose();+ document.dispose();+ },+ };+}diff --git a/packages/reconciler/tsconfig.json b/packages/reconciler/tsconfig.jsonnew file mode 100644index 00000000..516eda7b--- /dev/null+++ b/packages/reconciler/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.tsbuildinfo",+ "erasableSyntaxOnly": false,+ "lib": ["es2024", "DOM", "DOM.Iterable"],+ "types": ["@webgpu/types"]+ },+ "include": ["src"]+}diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.mdindex 679f9ee7..9ebb606f 100644--- a/packages/runtime/MIGRATION.md+++ b/packages/runtime/MIGRATION.md@@ -108,7 +108,7 @@ apps/web now depends on `@diffusionstudio/runtime` and `@diffusionstudio/koota-s- **Engine shell** (`apps/web/src/engine/`, not in this package — it's browser/DOM-coupled, which this package deliberately isn't): `Engine` (`create-engine.ts`) is a class wrapping `createRuntimeWorld` + `runSystems`; it owns canvas mount/resize/DPR, an AudioContext (created or injected, closed on `dispose()` only if it created it), and its own `requestAnimationFrame` loop (`start`/`stop`, plus a public `step(timestamp)` escape hatch for a future host to drive the tick itself and interleave app-side input/HUD systems around it). `context.tsx` (`EngineProvider`/`useEngineContext`) composes koota-solid's `WorldProvider` around `engine.world`, so trait state is read via `useTrait`/`useQuery` directly against the world, not funneled through a context bag. `canvas.tsx` (`EngineCanvas`) is the reusable mount/resize/start component. `hooks/` has a few illustrative per-trait wrappers so far: `useCamera`, `useActiveScene`, `useRunning`.- **Wired into the live app**: `KootaEngineProvider` (the new `EngineProvider`, aliased) is mounted in `pages/home.tsx` at the same level and lifetime as the old bitecs `EngineProvider` (both keyed on `projectId`), so anything under `EditorPage` can reach the koota world as more gets migrated. In `components/canvas/canvas.tsx`, the koota `EngineCanvas` now occupies the visible `z-1` canvas slot. The old bitecs `<canvas id="engine-canvas">` stays mounted at the same DOM id (so its `EngineProvider`'s `init()` still finds it and keeps initializing, and everything still on `useEngine()`/`useECS()` — Toolbar, drag/drop, sidebars, timeline — keeps working) but is `opacity-0 pointer-events-none`: no longer visible or interactive. Drag/drop handlers moved from the canvas element to its wrapping div so `pointer-events-none` didn't silently kill them.-- The koota world mounted this way is currently empty — no scene-loading/restore wiring exists yet, so this proves the canvas/audio/tick-loop plumbing end to end, not real project content.+- **Projects on disk (desktop only)**: `apps/web/src/projects/` loads real content into the koota world. A project is a folder under a user-picked root (persisted in `dspro.ui.projects.root`) holding an `index.tsx` whose default export renders `<stage>`; the electron main process (`apps/desktop/src/projects.ts`) scans the root, scaffolds new folders (`index.tsx`, `package.json`, `tsconfig.json`, generated `jsx.d.ts`), bundles with esbuild + babel-preset-solid (universal, moduleName `@diffusionstudio/jsx`) and watches for changes. The new `@diffusionstudio/reconciler` package (`packages/reconciler`, modeled on ds-next's `src/reconciler/`) evaluates the CJS bundle against the app's solid-js and `@diffusionstudio/jsx`, and its `RuntimeDocument` implements `ProjectDocument` over the world (`mount(code, world)` wraps both): `<stage>` = Scene entity (x/y/width/height), `<rect>` = RECT entity (x/y/width/height/fill as a solid Paint child). Host nodes wrap entities in objects because Solid's universal renderer treats numbers as text. `ProjectLoader` (mounted in `pages/home.tsx`) compiles → renders → refits the camera once → re-renders on disk changes; the project id in `?project=` is the folder name. Only those two tags/five props so far; no write-back from canvas edits to source yet.## Remaining work (suggested order)