Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance project management commands and documentation

konstantin-paulus963f3c1f6f8a
diff --git a/README.md b/README.md
index c77cc9a9..a3fd0c1c 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,7 @@ dapi node render -o hero.mp4 # encode the scene to disk
| Command | Purpose |
| --- | --- |
+| `dapi open` | Launch the app and open (or create) a project folder, anywhere on disk |
| `dapi context` | Summary of app state |
| `dapi capture` | Render a node in isolation to a labelled contact sheet, or one PNG per position |
| `dapi media …` | Inspect a file by id or path: `probe`, `grab`, `filmstrip`, `waveform`, `transcribe`, `listen` |
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index ea09d626..ffe2c5ae 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -3,6 +3,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 { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -10,7 +11,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
import { Command } from "commander";
import { version } from "../../../package.json";
import { parseTime, TIME_FPS } from "@diffusionstudio/jsx";
-import { editor, errnoCode, GENERATE_TIMEOUT_MS } from "./cli-client";
+import { editor, errnoCode, GENERATE_TIMEOUT_MS, waitForCliSocket } from "./cli-client";
import { listLocalFonts } from "./fonts";
import { buildIssueBody, createIssue } from "./report";
import { fetchVideo } from "./ytdlp";
@@ -315,6 +316,35 @@ async function captureNode(id: string, opts: CaptureOptions): Promise<void> {
}
}
+type OpenOptions = { background?: boolean };
+
+/** `open -a` on a running app only activates it, so this is safe to always run. */
+function launchApp(background: boolean): Promise<boolean> {
+ const args = background ? ["-g", "-a", APP_NAME, "--args", "--hidden"] : ["-a", APP_NAME];
+ return new Promise((res) => execFile("open", args, (err) => res(!err)));
+}
+
+async function openProject(path: string | undefined, opts: OpenOptions): Promise<void> {
+ // Launching is macOS's job; elsewhere (and when the app is not installed,
+ // e.g. a dev checkout run from the terminal) fall through to the socket,
+ // which answers if the app is running and errors usefully if not.
+ const launched = process.platform === "darwin" && (await launchApp(opts.background ?? false));
+
+ try {
+ // A cold launch needs the renderer up before the app can answer; when
+ // nothing was launched there is nothing to wait for, so fail fast.
+ if (launched) await waitForCliSocket();
+ else await editor.ping.query();
+
+ if (path !== undefined) {
+ const result = await editor.open.mutate({ dir: resolve(path) });
+ console.log(JSON.stringify(result));
+ }
+ } catch (e) {
+ handleSocketError(e);
+ }
+}
+
async function context(): Promise<void> {
try {
const result = await editor.context.query();
@@ -568,6 +598,15 @@ Use for any media analysis, media generation, or video editing task. No ffmpeg n
)
.version(version);
+program
+ .command("open")
+ .description(
+ `Launch ${APP_NAME} (or surface the running instance) and, given a path, open that folder as a project.`,
+ )
+ .argument("[path]", "project folder to open or create (default: none — just launch the app)")
+ .option("-b, --background", "launch or keep the app in the background, without raising a window")
+ .action((path: string | undefined, opts: OpenOptions) => openProject(path, opts));
+
program
.command("context")
.alias("ctx")
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index bd70d086..dc3e3a56 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -43,6 +43,7 @@ export const MAIN_CHANNELS = {
PROJECTS_PICK_ROOT: "projects:pick-root",
PROJECTS_LIST: "projects:list",
PROJECTS_GET: "projects:get",
+ PROJECTS_INIT: "projects:init",
PROJECTS_RESOLVE: "projects:resolve",
PROJECTS_CREATE: "projects:create",
PROJECTS_RENAME: "projects:rename",
@@ -141,6 +142,7 @@ export type MainRequestMap = {
[MAIN_CHANNELS.PROJECTS_PICK_ROOT]: { request: void; response: string | null };
[MAIN_CHANNELS.PROJECTS_LIST]: { request: { root: string }; response: ProjectInfo[] };
[MAIN_CHANNELS.PROJECTS_GET]: { request: { dir: string }; response: ProjectInfo | null };
+ [MAIN_CHANNELS.PROJECTS_INIT]: { request: { dir: string }; response: ProjectInfo };
[MAIN_CHANNELS.PROJECTS_RESOLVE]: {
request: { root: string; ref: string };
response: ProjectInfo | null;
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 2dd2a74d..3e62deae 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -19,6 +19,7 @@ import {
deleteProject,
duplicateProject,
getProject,
+ initProject,
listProjects,
pickRoot,
renameProject,
@@ -273,6 +274,7 @@ if (app.requestSingleInstanceLock()) {
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ root }) => listProjects(root));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_INIT, ({ dir }) => initProject(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ root, ref }) => resolveProject(root, ref));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>
createProject(root, displayName),
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 964e4d68..82f0ba0f 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -287,6 +287,7 @@ const SOLID_VERSION = "^1.9.10";
* subcommands have no top-level namesakes to collide with.
*/
const SCRIPTS: Record<string, string> = {
+ open: "dapi open .",
context: "dapi context",
capture: "dapi capture",
probe: "dapi media probe",
@@ -437,6 +438,7 @@ All of them talk to the running app, except \`fonts\` and \`fetch\`.
| Script | Command | What it does |
| ------ | ------- | ------------ |
+| \`open\` | \`dapi open .\` | Launch the app with this project open. |
| \`context\` | \`dapi context\` | Which project the app has open, where its playhead sits, its fonts. |
| \`capture\` | \`dapi capture <id>\` | Render one node in isolation to labelled PNG contact sheets. |
| \`probe\` | \`dapi media probe <id\\|path>\` | Container and per-track metadata, without decoding. |
@@ -517,6 +519,24 @@ export async function scaffold(dir: string, displayName = basename(dir)): Promis
}
}
+/**
+ * Makes `dir` openable as a project, writing as little as that takes: the
+ * folder if it does not exist, and — when nothing in it can be an entry — an
+ * `index.tsx` holding an empty stage. Nothing else; a project is its JSX, and
+ * the record, manifest, and the rest of the scaffold appear lazily, each when
+ * something first needs it. A folder that is already a project comes back
+ * untouched. How `dapi open <path>` opens a folder anywhere on disk.
+ */
+export async function initProject(dir: string): Promise<ProjectInfo> {
+ await mkdir(dir, { recursive: true });
+ if (!(await findEntry(dir))) {
+ await writeIfMissing(dir, "index.tsx", STARTER);
+ }
+ const project = await describe(dir);
+ if (!project) throw new Error(noEntryError());
+ return project;
+}
+
/**
* 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
diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsx
index 6fef68ae..1b5913e6 100644
--- a/apps/web/src/app.tsx
+++ b/apps/web/src/app.tsx
@@ -10,6 +10,7 @@ import { AppContextMenu } from "@/components/app-context-menu";
import { AuthProvider, useAuth } from '@/context/auth';
import { PersistRoute } from '@/lib/persist-route';
+import { ShellApi } from '@/context/dapi/shell';
import { UpgradeDialog } from '@/components/upgrade-dialog';
import { PurchaseSuccess } from '@/components/purchase-success';
import { ScreenTooSmall } from '@/components/screen-too-small';
@@ -75,6 +76,7 @@ function App() {
<Toaster />
<EnvironmentOverlays />
<PersistRoute />
+ <ShellApi />
</ColorModeProvider>
)}
>
diff --git a/apps/web/src/context/dapi/api.tsx b/apps/web/src/context/dapi/api.tsx
index 706ea5a8..3c0a83e8 100644
--- a/apps/web/src/context/dapi/api.tsx
+++ b/apps/web/src/context/dapi/api.tsx
@@ -8,6 +8,7 @@ import { Project } from '@diffusionstudio/runtime';
import { useProject } from '@/context/project';
import { useAuth } from '@/context/auth';
import { t, q, q0 } from "@/lib/cli-rpc";
+import type { ShellRouter } from "./shell";
import { handleContextGet } from "./context";
import { handleMediaProbe, handleMediaFrame, handleMediaTranscribe, handleMediaFilmstrip, handleMediaWaveform, handleMediaListen } from "./media";
import { handleCapture } from "./capture";
@@ -83,7 +84,6 @@ type AppRouterDeps = {
function createAppRouter({ world, project, getUser, requireAuth }: AppRouterDeps) {
return t.router({
- ping: t.procedure.query(() => {}),
whoami: t.procedure.query(() => getUser()),
context: q0(handleContextGet(world, project)),
capture: q(handleCapture(world)),
@@ -102,7 +102,7 @@ function createAppRouter({ world, project, getUser, requireAuth }: AppRouterDeps
});
}
-export type AppRouter = ReturnType<typeof createAppRouter>;
+export type AppRouter = ShellRouter & ReturnType<typeof createAppRouter>;
export function useEditorApi() {
const ctx = useContext(EditorApiContext);
diff --git a/apps/web/src/context/dapi/shell.tsx b/apps/web/src/context/dapi/shell.tsx
new file mode 100644
index 00000000..e820fa86
--- /dev/null
+++ b/apps/web/src/context/dapi/shell.tsx
@@ -0,0 +1,44 @@
+/* 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 { onCleanup } from "solid-js";
+import { useNavigate } from "@solidjs/router";
+
+import { t, m, createRouterCaller } from "@/lib/cli-rpc";
+import { cliBridge } from "@/lib/ipc";
+import { openProjectFolder } from "@/projects";
+import { projectRoute } from "@/hooks/use-project-route";
+
+import type { Navigator } from "@solidjs/router";
+
+type ShellRouterDeps = {
+ navigate: Navigator;
+};
+
+/**
+ * The CLI procedures that outlive any one project: what `dapi` can ask of the
+ * app while it sits at the dashboard, or before anything is open at all. The
+ * editor's own router (see ./api) mounts per project; this one is registered
+ * for as long as the app runs, which is what lets `ping` prove the app is up
+ * and `open` bring a project in from nothing.
+ */
+export function createShellRouter({ navigate }: ShellRouterDeps) {
+ return t.router({
+ ping: t.procedure.query(() => {}),
+ open: m(async ({ dir }: { dir: string }) => {
+ const project = await openProjectFolder(dir);
+ navigate(projectRoute(project.id || project.name));
+ return { id: project.id, name: project.displayName, dir: project.dir };
+ }),
+ });
+}
+
+export type ShellRouter = ReturnType<typeof createShellRouter>;
+
+/** Registers the shell router for the app's lifetime. Renders nothing; must sit inside the router tree for `useNavigate`. */
+export function ShellApi() {
+ const navigate = useNavigate();
+ onCleanup(cliBridge.register(createRouterCaller(createShellRouter({ navigate }))));
+ return null;
+}
diff --git a/apps/web/src/lib/db.ts b/apps/web/src/lib/db.ts
index 87fd64d1..a96b2007 100644
--- a/apps/web/src/lib/db.ts
+++ b/apps/web/src/lib/db.ts
@@ -22,6 +22,13 @@ export function generateProjectName(): string {
return `${adj} ${noun} ${day} ${month}`;
}
+/**
+ * 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
@@ -35,10 +42,14 @@ 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' });
+
/**
* The bundle a project last mounted successfully, keyed by its id. Two jobs:
* the copy an export re-renders (see `@/engine/capture`), and the head start
@@ -91,37 +102,49 @@ const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {
const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
/**
- * 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.
+ * 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.
*/
-export async function rememberProjectRoot(path: string): Promise<ProjectRoot> {
+export async function rememberProjectRoot(path: string, kind: ProjectRootKind = 'multi'): Promise<ProjectRoot> {
const db = await dbPromise;
const now = new Date().toISOString();
const existing = await db.getFromIndex('roots', 'by-path', path);
const root: ProjectRoot = existing
- ? { ...existing, name: folderLabel(path), lastUsedAt: now }
- : { id: nanoid(), path, name: folderLabel(path), createdAt: now, lastUsedAt: now };
+ ? { ...normalizeRoot(existing), name: folderLabel(path), kind, lastUsedAt: now }
+ : { id: nanoid(), path, name: folderLabel(path), kind, createdAt: now, lastUsedAt: now };
await db.put('roots', root);
return root;
}
-/** Every projects root, most recently used first. */
-export async function listProjectRoots(): Promise<ProjectRoot[]> {
+/** Every projects root — of `kind`, when given — most recently used first. */
+export async function listProjectRoots(kind?: ProjectRootKind): Promise<ProjectRoot[]> {
const db = await dbPromise;
- return (await db.getAllFromIndex('roots', 'by-last-used')).reverse();
+ const roots = (await db.getAllFromIndex('roots', 'by-last-used')).reverse().map(normalizeRoot);
+ return kind ? roots.filter((root) => root.kind === kind) : roots;
}
-/** The root the app is working against: the one used last, or null when there is none. */
+/**
+ * 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.
+ */
export async function lastUsedProjectRoot(): Promise<ProjectRoot | null> {
const db = await dbPromise;
- const cursor = await db
+ let cursor = await db
.transaction('roots', 'readonly')
.store.index('by-last-used')
.openCursor(null, 'prev');
- return cursor?.value ?? null;
+ while (cursor) {
+ const root = normalizeRoot(cursor.value);
+ if (root.kind === 'multi') return root;
+ cursor = await cursor.continue();
+ }
+ return null;
}
/** Forgets a projects root. The folder itself is left alone. */
diff --git a/apps/web/src/lib/ipc.ts b/apps/web/src/lib/ipc.ts
index e75948d1..98b61761 100644
--- a/apps/web/src/lib/ipc.ts
+++ b/apps/web/src/lib/ipc.ts
@@ -105,7 +105,10 @@ type PendingCliRequest = { req: CliRequest; ws: WebSocket };
// mounts (or between remounts on project switches) are held and retried on
// the next registration — no explicit ready signal needed.
class CliBridge {
- private router: RouterCaller | null = null;
+ // Several routers coexist: the shell router (always mounted, owns `ping`
+ // and `open`) and the editor router (mounted per open project). Paths are
+ // disjoint; a request is answered by whichever router owns its path.
+ private routers = new Set<RouterCaller>();
private pending: PendingCliRequest[] = [];
constructor() {
@@ -128,9 +131,17 @@ class CliBridge {
}
}
+ private resolve(path: string): ProcedureCaller | undefined {
+ for (const router of this.routers) {
+ const proc = router(path);
+ if (proc) return proc;
+ }
+ return undefined;
+ }
+
private async dispatch(pending: PendingCliRequest): Promise<void> {
const { req, ws } = pending;
- const proc = this.router?.(req.path);
+ const proc = this.resolve(req.path);
if (!proc) {
this.pending.push(pending);
return;
@@ -156,12 +167,12 @@ class CliBridge {
register(router: RouterCaller): () => void {
if (!window.desktop) return () => {};
- this.router = router;
+ this.routers.add(router);
const held = this.pending;
this.pending = [];
for (const pending of held) void this.dispatch(pending);
return () => {
- if (this.router === router) this.router = null;
+ this.routers.delete(router);
};
}
}
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index 44f4e62b..495363a4 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -18,7 +18,7 @@ import { createSignal } from 'solid-js';
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { mainBridge } from '@/lib/ipc';
-import { lastUsedProjectRoot, rememberProjectRoot } from '@/lib/db';
+import { lastUsedProjectRoot, listProjectRoots, rememberProjectRoot } from '@/lib/db';
import type { CompileResult, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';
@@ -91,15 +91,48 @@ export async function createProject(displayName: string): Promise<ProjectInfo> {
}
/**
- * The project `ref` names under the root: its id, or — for links made before
- * ids existed, and folders opened by name — its folder name. What comes back
- * always carries an id, so the app can put that in the URL.
+ * 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.
*/
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;
+ }
+ return 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.
+ */
+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();
- if (!root || !isDesktop()) return null;
- return mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { root, ref });
+ const underRoot = root !== null && project.dir.startsWith(root.replace(/[\/]+$/, '') + '/');
+ if (!underRoot) await rememberProjectRoot(project.dir, 'single');
+
+ return project;
}
/** The project in the folder `dir`, or null when there is none. */
diff --git a/reference/README.md b/reference/README.md
index d48ca86d..4476ce72 100644
--- a/reference/README.md
+++ b/reference/README.md
@@ -28,6 +28,7 @@ How the surface is divided:
### Document
+- [`dapi open`](./open.md): launch the app and open (or create) a project folder, anywhere on disk
- [`dapi context`](./context.md): which project the app has open, where its playhead sits, and its registered fonts
- [`dapi capture`](./capture.md): render a node in isolation to a labelled contact sheet, or one PNG per position
diff --git a/reference/open.md b/reference/open.md
new file mode 100644
index 00000000..934ee176
--- /dev/null
+++ b/reference/open.md
@@ -0,0 +1,48 @@
+# `dapi open [path]`
+
+Launches Diffusion Studio — or surfaces the running instance — and, given a
+path, opens that folder as a project. The first command of the core loop:
+`open`, then mount, then render.
+
+The folder may live anywhere on disk, and does not have to be a project yet.
+Opening is what makes it one, writing as little as that takes:
+
+- a missing folder is created;
+- a folder with no entry file (package.json `main`, or `index.tsx` and
+ friends) gains an `index.tsx` holding an empty stage.
+
+Nothing else is written — no package.json, tsconfig, README, or manifest. A
+project is its JSX; the rest of the scaffold appears lazily, each piece when
+something first needs it. A folder that is already a project is opened
+untouched, wherever it lives.
+
+The app remembers the folder, so the project reopens across app relaunches
+and stays addressable by folder name or project id.
+
+## Input
+
+- `[path]`: project folder to open or create (optional; with no path the
+ command just makes sure the app is up). Relative paths resolve against the
+ shell's working directory.
+- `-b, --background`: launch or keep the app in the background, without
+ raising a window. The way to drive the editor headless.
+
+## Output
+
+With a path, the opened project as one JSON object:
+
+```ts
+{
+ id: string; // package.json `projectId`; "" until the project has a record
+ name: string; // display name (falls back to the folder name)
+ dir: string; // absolute project folder, as opened
+}
+```
+
+With no path, nothing: exit code `0` says the app is up.
+
+## Errors
+
+- The path exists but is not a folder.
+- Off macOS, the app cannot be launched; the command then requires it to
+ already be running.