Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor asset reference handling and improve media command descriptions

konstantin-paulus3099d1c1224a
diff --git a/apps/cli/src/cli-channels.ts b/apps/cli/src/cli-channels.ts
index 5b6161bf..f2c2d2c5 100644
--- a/apps/cli/src/cli-channels.ts
+++ b/apps/cli/src/cli-channels.ts
@@ -30,7 +30,7 @@ export type CliReply =
| { ok: true; data: unknown }
| { ok: false; error: string };
-export type AssetRef = { id: string } | { path: string };
+export type AssetRef = { path: string };
export type MediaProbeRequest = AssetRef;
diff --git a/apps/cli/src/cli-client.ts b/apps/cli/src/cli-client.ts
index 7f2c845f..6e2d3f6d 100644
--- a/apps/cli/src/cli-client.ts
+++ b/apps/cli/src/cli-client.ts
@@ -143,7 +143,7 @@ export function errnoCode(e: unknown): string | undefined {
// Bridges the cold-start gap after launching the app. Main only delivers the
// handshake once the renderer has finished loading, and `ping` is answered
-// by the always-mounted auth router, so a single round-trip proves the app is
+// by the always-mounted app router, so a single round-trip proves the app is
// fully up. The retry loop only handles the brief window before the handshake
// socket itself binds (ENOENT/ECONNREFUSED).
export async function waitForCliSocket(timeoutMs = 30000): Promise<void> {
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index e8033d55..aa6874e1 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -124,19 +124,18 @@ async function mediaFrame(ref: string, opts: MediaFrameOptions): Promise<void> {
}
/**
- * An asset id, a local file (or frames folder) that exists, or otherwise a
- * library path (`b-roll/clip.mp4`) for the app to look up.
+ * A local file (or frames folder) that exists is sent as its absolute path;
+ * anything else — a URL, or a library path (`b-roll/clip.mp4`) — is passed
+ * through for the app to resolve. Library paths need an open project.
*/
function resolveAssetRef(ref: string): AssetRef {
- if (/^[A-Za-z0-9]+$/.test(ref)) return { id: ref };
-
const absPath = isAbsolute(ref) ? ref : resolve(process.cwd(), ref);
if (existsSync(absPath)) return { path: absPath };
if (isAbsolute(ref)) {
console.error(`File not found: ${absPath}`);
process.exit(1);
}
- return { id: ref };
+ return { path: ref };
}
async function mediaProbe(ref: string): Promise<void> {
@@ -598,7 +597,7 @@ program
.command("context")
.alias("ctx")
.description(
- `Print the current app context: which project the app has open (id, display name, folder), where its playhead sits, in seconds, the registered font families, and where its generations stand.`,
+ `Print the current app context: which project the app has open (id, display name, folder — or null when none is), where its playhead sits, in seconds, the registered font families, and where its generations stand.`,
)
.action(() => context());
@@ -618,7 +617,7 @@ const media = program
.command("media")
.alias("m")
.description(
- "Inspect a media file by asset id or local path, without adding it to the project: probe metadata, transcribe speech, grab frames, render visual previews, and analyze with multimodal models.",
+ "Inspect a media file by path, without adding it to the project: probe metadata, transcribe speech, grab frames, render visual previews, and analyze with multimodal models. Local files work with or without an open project; library paths need one.",
);
media
@@ -626,7 +625,7 @@ media
.description(
`Read the container and per-track technical metadata of a media file (local read, no credits): container format, duration, tags, and each track's codec params, without decoding. Commonly useful for a quick technical read, e.g. checking codec compatibility or duration before cutting. Packet stats (fps, bitrate) are estimated from a leading sample; images and transcripts report file-level info only.`,
)
- .argument("<id|path>", "asset id, or a local file")
+ .argument("<path>", "local file path")
.action((ref: string) => mediaProbe(ref));
media
@@ -634,7 +633,7 @@ media
.description(
`Transcribe the speech in a video or audio file and print the timed transcript, with word-level start/end times in seconds. Commonly useful for footage with speakers (talking head, interview), where the word times let you cut on a line. A transcript marks only speech; the gaps are not necessarily silent (music, score, applause).`,
)
- .argument("<id|path>", "video or audio asset id, or a local file")
+ .argument("<path>", "local video or audio file path")
.action((ref: string) => mediaTranscribe(ref));
media
@@ -643,7 +642,7 @@ media
.description(
`Decode frames of a video file and write them as PNGs (local render, no credits). By default the frames are merged into contact sheets: up to 12 per image, each cell labelled with its timecode (\`08s10f\`, zero segments dropped) and drawn as large as fits, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one (\`--separate\` writes a PNG per frame). Grabs the asset's own pixels, unlike \`capture\` which renders the composited node. The recommended tool for understanding a video at the frame level; past ~12 frames prefer \`media filmstrip\`.`,
)
- .argument("<id|path>", "video asset id, or a local video file to grab frames from")
+ .argument("<path>", "local video file path to grab frames from")
.option("-t, --time <time...>", `one or more timestamps to grab — seconds ("1.5"), frames ("45f"), or "MM:SS"; negatives count back from the end, so -1 is one second before the end and -1f one frame before it (default: 0)`)
.option("-c, --count <n>", "instead of --time, grab this many frames evenly spaced across the clip (or across the --start/--end window)")
.option("-a, --auto", "scan the clip at 2fps and keep a frame each time the footage settles into a new visual state (transitions are waited out, so picks stay sharp); returns at most --count frames (default cap: 30), static footage like screen recordings returns far fewer; requires WebGPU")
@@ -662,7 +661,7 @@ media
.description(
`Render a grid of thumbnails sampled across the timeline to a PNG (local render, no credits), each row stamped with an HH:MM:SS:FF ruler. A fast, token-efficient video track preview; narrow the window to zoom into a region of interest. Video only (use \`media waveform\` for audio).`,
)
- .argument("<id|path>", "video asset id, or a local video file to preview")
+ .argument("<path>", "local video file path to preview")
.option("-s, --start <time>", `start of the window to preview — seconds, "45f" frames, or "MM:SS" (default: 0)`)
.option("-e, --end <time>", `end of the window to preview — seconds, "45f" frames, or "MM:SS" (default: asset duration)`)
.option("-x, --scale <factor>", "scale factor for the thumbnails; smaller thumbnails fit more rows and columns, larger fit fewer (default: 1)")
@@ -675,7 +674,7 @@ media
.description(
`Render the audio track of a video or audio file as a waveform PNG (local render, no credits) with a timestamp ruler: loudness over time, with silent stretches highlighted in red. A fast, token-efficient audio track preview; the silent spans are also returned as second ranges.`,
)
- .argument("<id|path>", "video or audio asset id, or a local file to preview")
+ .argument("<path>", "local video or audio file path to preview")
.option("-s, --start <time>", `start of the window to preview — seconds, "45f" frames, or "MM:SS" (default: 0)`)
.option("-e, --end <time>", `end of the window to preview — seconds, "45f" frames, or "MM:SS" (default: asset duration)`)
.option("-x, --scale <factor>", "scale factor for the waveform; smaller fits more rows and columns, larger fits fewer (default: 1)")
@@ -687,7 +686,7 @@ media
.description(
`Prompt a multimodal model for a semantic analysis of an audio track and print its answer. Shines on audio semantics (the name of the music playing, who is speaking, the spoken content with second-granularity timestamps). Accepts an audio file or a video; by default only the audio track is analyzed.`,
)
- .argument("<id|path>", "video or audio asset id, or a local file to analyze")
+ .argument("<path>", "local video or audio file path to analyze")
.option("-p, --prompt <str>", "question or instruction to guide the analysis")
.option("-s, --start <time>", `start of the segment to analyze — seconds, "45f" frames, or "MM:SS" (default: 0); timestamps in the analysis are relative to this point`)
.option("-e, --end <time>", `end of the segment to analyze — seconds, "45f" frames, or "MM:SS" (default: media duration)`)
diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsx
index 1b5913e6..a1a58616 100644
--- a/apps/web/src/app.tsx
+++ b/apps/web/src/app.tsx
@@ -10,7 +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 { EditorApi } from '@/context/dapi';
import { UpgradeDialog } from '@/components/upgrade-dialog';
import { PurchaseSuccess } from '@/components/purchase-success';
import { ScreenTooSmall } from '@/components/screen-too-small';
@@ -71,12 +71,12 @@ function App() {
<BootSplash />
<UpgradeDialog />
<PurchaseSuccess />
+ <EditorApi />
</AuthProvider>
</AppContextMenu>
<Toaster />
<EnvironmentOverlays />
<PersistRoute />
- <ShellApi />
</ColorModeProvider>
)}
>
diff --git a/apps/web/src/context/dapi/api.tsx b/apps/web/src/context/dapi/api.tsx
index 52cb2b83..d0697101 100644
--- a/apps/web/src/context/dapi/api.tsx
+++ b/apps/web/src/context/dapi/api.tsx
@@ -3,28 +3,30 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { createEffect, createContext, useContext, onCleanup } from "solid-js";
+import { useNavigate } from "@solidjs/router";
import { useWorld } from '@diffusionstudio/koota-solid';
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 { t, q, q0, m } from "@/lib/cli-rpc";
+import { editorSession, requireEditorSession, setEditorSession } from "./session";
import { handleContextGet } from "./context";
-import { handleMediaProbe, handleMediaFrame, handleMediaTranscribe, handleMediaFilmstrip, handleMediaWaveform, handleMediaListen } from "./media";
+import { createAssetResolver, handleMediaProbe, handleMediaFrame, handleMediaTranscribe, handleMediaFilmstrip, handleMediaWaveform, handleMediaListen } from "./media";
import { handleCapture } from "./capture";
import { handleLogs } from "./logs";
import { handleModels } from "./models";
import { handleVoices } from "./voices";
import { cliBridge } from '@/lib/ipc';
import { createRouterCaller } from '@/lib/cli-rpc';
+import { openProjectFolder } from '@/projects';
+import { projectRoute } from '@/hooks/use-project-route';
import { assert } from "@/utils/common";
import { handleWindowScreenshot } from "./window";
import { useFullscreenState } from "@/hooks/use-fullscreen-state";
import type { JSX, Accessor } from 'solid-js';
+import type { Navigator } from '@solidjs/router';
import type { User } from '@supabase/supabase-js';
-import type { World } from 'koota';
-import type { ProjectContextValue } from '@/context/project';
type EditorApiProviderProps = {
children: JSX.Element;
@@ -37,10 +39,16 @@ type EditorApiContextValue = {
const EditorApiContext = createContext<EditorApiContextValue>();
-export function EditorApiProvider(props: EditorApiProviderProps) {
- const project = useProject();
+/**
+ * The one CLI router, registered for as long as the app runs. Every endpoint
+ * is reachable whether or not a project is open; the ones that need one read
+ * the session slot (see ./session) per request and fail with a clear error —
+ * or, for `context`, report that nothing is open. Renders nothing; must sit
+ * inside the router tree for `useNavigate` and inside the auth provider.
+ */
+export function EditorApi() {
+ const navigate = useNavigate();
const auth = useAuth();
- const isFullscreen = useFullscreenState();
const requireAuth = <I, O>(fn: (data: I) => Promise<O>) => (data: I) => {
assert(auth.isAuthenticated(), "Sign in required: AI generation needs a Diffusion Studio account.");
@@ -53,13 +61,26 @@ export function EditorApiProvider(props: EditorApiProviderProps) {
return user;
};
+ const router = createAppRouter({ navigate, getUser, requireAuth });
+ onCleanup(cliBridge.register(createRouterCaller(router)));
+ return null;
+}
+
+/**
+ * Publishes the editor session for the CLI router while the project is open,
+ * and provides the editor UI's own view of the app shell (fullscreen state,
+ * desktop-ness). Mounted per project page.
+ */
+export function EditorApiProvider(props: EditorApiProviderProps) {
+ const project = useProject();
+ const isFullscreen = useFullscreenState();
const world = useWorld();
createEffect(() => {
if (!window.desktop || project.id() !== world.get(Project)?.id) return;
- const router = createAppRouter({ world, project, getUser, requireAuth });
- onCleanup(cliBridge.register(createRouterCaller(router)));
+ setEditorSession({ world, project });
+ onCleanup(() => setEditorSession(null));
});
return (
@@ -76,33 +97,40 @@ export function EditorApiProvider(props: EditorApiProviderProps) {
type AppRouterDeps = {
- world: World;
- project: ProjectContextValue;
+ navigate: Navigator;
getUser: () => User;
requireAuth: <I, O>(fn: (data: I) => Promise<O>) => (data: I) => Promise<O>;
};
-function createAppRouter({ world, project, getUser, requireAuth }: AppRouterDeps) {
+function createAppRouter({ navigate, getUser, requireAuth }: AppRouterDeps) {
+ const resolveAsset = createAssetResolver(editorSession);
+
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 };
+ }),
whoami: t.procedure.query(() => getUser()),
- context: q0(handleContextGet(world, project)),
- capture: q(handleCapture(world, project)),
+ context: q0(handleContextGet(editorSession)),
+ capture: q(handleCapture(requireEditorSession)),
models: q(handleModels()),
logs: q(handleLogs()),
screenshot: q0(handleWindowScreenshot()),
voices: q0(handleVoices()),
media: t.router({
- probe: q(handleMediaProbe(world)),
- frame: q(handleMediaFrame(world)),
- transcribe: q(handleMediaTranscribe(world)),
- filmstrip: q(handleMediaFilmstrip(world)),
- waveform: q(handleMediaWaveform(world)),
- listen: q(requireAuth(handleMediaListen(world))),
+ probe: q(handleMediaProbe(resolveAsset)),
+ frame: q(handleMediaFrame(resolveAsset)),
+ transcribe: q(handleMediaTranscribe(resolveAsset)),
+ filmstrip: q(handleMediaFilmstrip(resolveAsset)),
+ waveform: q(handleMediaWaveform(resolveAsset)),
+ listen: q(requireAuth(handleMediaListen(resolveAsset, editorSession))),
}),
});
}
-export type AppRouter = ShellRouter & ReturnType<typeof createAppRouter>;
+export type AppRouter = ReturnType<typeof createAppRouter>;
export function useEditorApi() {
const ctx = useContext(EditorApiContext);
diff --git a/apps/web/src/context/dapi/capture.ts b/apps/web/src/context/dapi/capture.ts
index a5a623ef..024515fd 100644
--- a/apps/web/src/context/dapi/capture.ts
+++ b/apps/web/src/context/dapi/capture.ts
@@ -17,7 +17,7 @@ import { createCapture } from "@/engine/capture";
import type { CaptureRequest, CaptureResult, TimecodedImage } from "@diffusionstudio/cli/channels";
import type { Entity, World } from "koota";
-import type { ProjectContextValue } from "@/context/project";
+import type { EditorSession } from "./session";
// Scenes are nodes too, so capture accepts them alongside geometry, groups,
// and adjustment layers.
@@ -64,8 +64,9 @@ function resolveNode(world: World, id: string): Entity {
// Ceiling on the height a sheet cell renders a node at.
const SHEET_CAPTURE_HEIGHT = 1080;
-export function handleCapture(world: World, project: ProjectContextValue) {
+export function handleCapture(session: () => EditorSession) {
return async ({ id, frames, combine = true, perSheet }: CaptureRequest): Promise<CaptureResult> => {
+ const { world, project } = session();
const node = resolveNode(world, id);
// `undefined` means the node's first visible frame (the encoder's frame 0).
diff --git a/apps/web/src/context/dapi/context.ts b/apps/web/src/context/dapi/context.ts
index 19cb34b7..dc5a8e7a 100644
--- a/apps/web/src/context/dapi/context.ts
+++ b/apps/web/src/context/dapi/context.ts
@@ -4,28 +4,24 @@
import { AssetId, Computed, Fonts, FrameRate, Generating, getActiveEntity, Library, Name, PendingSource, Source, SourceError } from "@diffusionstudio/runtime";
+import type { Accessor } from "solid-js";
import type { Entity, World } from "koota";
-
-/**
- * The open project's identity, as the editor knows it. Structural on purpose:
- * this is the project context's shape, without the handler having to depend on
- * the Solid context it comes from.
- */
-type OpenProject = {
- id: () => string;
- dir: () => string;
- name: () => string;
-};
+import type { EditorSession } from "./session";
/**
* What `dapi context` reports: 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 project the app has open, where its playhead sits, which
- * font families are actually registered in the world drawing it
+ * font families are actually registered in the world drawing it. With no
+ * project open there is none of that to report, and the report says so.
*/
-export function handleContextGet(world: World, project: OpenProject) {
+export function handleContextGet(session: Accessor<EditorSession | null>) {
return async () => {
+ const open = session();
+ if (!open) return { project: null };
+
+ const { world, project } = open;
const frameRate = world.get(FrameRate)?.value || 30;
const active = getActiveEntity(world);
diff --git a/apps/web/src/context/dapi/media.ts b/apps/web/src/context/dapi/media.ts
index 0e6bdaf6..74cab872 100644
--- a/apps/web/src/context/dapi/media.ts
+++ b/apps/web/src/context/dapi/media.ts
@@ -9,30 +9,41 @@ import { uploadBlob } from '@/lib/uploads';
import { composeSheet, planSheet, planSheetSizes, sheetTimecode } from '@diffusionstudio/encoder';
import { assert } from '@/utils';
import { startResumableSession, uploadResumableStream } from '@/lib/uploads';
-import { filmstripAsset, formatTimecode, getAsset, getAssetFile, getLibrary, Project, transcodeForAnalysis, transcodeForTranscription, waveformAsset } from '@diffusionstudio/runtime';
-import { assetName } from '@diffusionstudio/assets';
+import { filmstripAsset, formatTimecode, getAssetFile, getLibrary, Project, transcodeForAnalysis, transcodeForTranscription, waveformAsset } from '@diffusionstudio/runtime';
+import { AssetLibrary, assetName, isAbsoluteSource, isUrlSource } from '@diffusionstudio/assets';
+import { createProjectFS } from '@/projects/fs';
-import type { World } from 'koota';
+import type { Accessor } from 'solid-js';
import type { Asset } from '@diffusionstudio/assets';
-import type { MediaListenRequest, MediaListenResult, MediaFrameRequest, MediaFrameResult, TimecodedImage, MediaProbeRequest, AssetRef, MediaTranscribeRequest, MediaTranscribeResult, MediaFilmstripRequest, MediaFilmstripResult, MediaWaveformRequest, MediaWaveformResult, TranscriptSegment } from "@diffusionstudio/cli/channels";
+import type { EditorSession } from './session';
+import type { MediaListenRequest, MediaListenResult, MediaFrameRequest, MediaFrameResult, TimecodedImage, MediaProbeRequest, MediaTranscribeRequest, MediaTranscribeResult, MediaFilmstripRequest, MediaFilmstripResult, MediaWaveformRequest, MediaWaveformResult, TranscriptSegment } from "@diffusionstudio/cli/channels";
+
+type ResolveAsset = (path: string) => Promise<Asset>;
/**
- * Resolves a command target: an id (or library path) looks up the project's
- * asset library; a path is described in place through the library without
- * being added to it (a transient asset).
+ * Resolves a command target by path. With a project open, its library answers:
+ * library paths look assets up, absolute paths and URLs are described in place
+ * without being added (transient assets). With none open, a throwaway library
+ * over a project-less FS describes absolute paths and URLs the same way — a
+ * fresh one per request, so nothing is remembered between calls.
*/
-async function resolveAssetRef(world: World, ref: AssetRef): Promise<Asset> {
- if ("path" in ref) return getLibrary(world).resolve(ref.path);
- const asset = getAsset(world, ref.id);
- assert(asset, `Asset ${ref.id} not found.`);
- return asset;
+export function createAssetResolver(session: Accessor<EditorSession | null>): ResolveAsset {
+ return (path) => {
+ const world = session()?.world;
+ if (world) return getLibrary(world).resolve(path);
+ assert(
+ isAbsoluteSource(path) || isUrlSource(path),
+ `Could not resolve "${path}": with no project open only absolute paths and URLs resolve — run \`dapi open <dir>\` to use library paths.`,
+ );
+ return new AssetLibrary(createProjectFS("")).resolve(path);
+ };
}
const PROBE_SAMPLE_PACKETS = 200;
-export function handleMediaProbe(world: World) {
+export function handleMediaProbe(resolve: ResolveAsset) {
return async (req: MediaProbeRequest): Promise<unknown> => {
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const blob = await getAssetFile(asset);
const base = {
@@ -107,11 +118,11 @@ const FRAME_QUALITY_BUDGETS = {
// Default cap on frames returned by auto selection when `count` is not given.
const AUTO_MAX_FRAMES = 30;
-export function handleMediaFrame(world: World) {
+export function handleMediaFrame(resolve: ResolveAsset) {
return async (req: MediaFrameRequest): Promise<MediaFrameResult> => {
const { times, count, start, end, quality, auto } = req;
const combine = req.combine ?? true;
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const id = asset.id;
assert(asset.type === "VIDEO", `Asset ${id} is not a video.`);
@@ -244,9 +255,9 @@ export function handleMediaFrame(world: World) {
const transcripts = new Map<string, TranscriptSegment[]>();
-export function handleMediaTranscribe(world: World) {
+export function handleMediaTranscribe(resolve: ResolveAsset) {
return async (req: MediaTranscribeRequest): Promise<MediaTranscribeResult> => {
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const id = asset.id;
assert(
asset.type === "AUDIO" || asset.type === "VIDEO",
@@ -272,29 +283,29 @@ export function handleMediaTranscribe(world: World) {
};
}
-export function handleMediaFilmstrip(world: World) {
+export function handleMediaFilmstrip(resolve: ResolveAsset) {
return async (req: MediaFilmstripRequest): Promise<MediaFilmstripResult> => {
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const { dataUrl, ...rest } = await filmstripAsset(asset, { start: req.start, end: req.end, scale: req.scale });
const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);
return { base64, ...rest };
};
}
-export function handleMediaWaveform(world: World) {
+export function handleMediaWaveform(resolve: ResolveAsset) {
return async (req: MediaWaveformRequest): Promise<MediaWaveformResult> => {
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const { dataUrl, ...rest } = await waveformAsset(asset, { start: req.start, end: req.end, scale: req.scale });
const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);
return { base64, ...rest };
};
}
-export function handleMediaListen(world: World) {
+export function handleMediaListen(resolve: ResolveAsset, session: Accessor<EditorSession | null>) {
return async (req: MediaListenRequest): Promise<MediaListenResult> => {
const { prompt, start, end } = req;
let { stripVideo } = req;
- const asset = await resolveAssetRef(world, req);
+ const asset = await resolve(req.path);
const id = asset.id;
assert(
asset.type === "AUDIO" || asset.type === "VIDEO",
@@ -308,7 +319,7 @@ export function handleMediaListen(world: World) {
asset.type === "VIDEO" ? (stripVideo ? "audio/ogg" : "video/mp4") : "audio/ogg";
const window = hasWindow ? `-${start ?? 0}-${end ?? "end"}` : "";
- const uploadId = `${world.get(Project)?.id ?? "project"}-${id}-analyze${stripVideo ? "-audio" : ""}${window}`
+ const uploadId = `${session()?.world.get(Project)?.id ?? "project"}-${id}-analyze${stripVideo ? "-audio" : ""}${window}`
.replace(/[^A-Za-z0-9._-]/g, "_");
const { uploadUrl, fileRef } = await trpc.getUploadUrl.mutate({
action: "resumable",
diff --git a/apps/web/src/context/dapi/session.ts b/apps/web/src/context/dapi/session.ts
new file mode 100644
index 00000000..b2601b38
--- /dev/null
+++ b/apps/web/src/context/dapi/session.ts
@@ -0,0 +1,43 @@
+/* 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 CLI router mounts once for the app's lifetime (see ./api); what changes
+// as projects open and close is this slot. The editor publishes its world and
+// project here while it is mounted, and project-bound endpoints read the slot
+// per request instead of closing over a world at registration time.
+
+import { createSignal } from "solid-js";
+import { assert } from "@/utils/common";
+
+import type { Accessor } from "solid-js";
+import type { World } from "koota";
+
+/**
+ * The open project's identity, as the editor knows it. Structural on purpose:
+ * this is the project context's shape, without the handlers having to depend
+ * on the Solid context it comes from.
+ */
+export type OpenProject = {
+ id: () => string;
+ dir: () => string;
+ name: () => string;
+};
+
+/** What only an open project can offer: the world drawing it, and which project that is. */
+export type EditorSession = { world: World; project: OpenProject };
+
+const [session, setSession] = createSignal<EditorSession | null>(null);
+
+/** The open project's session; null at the dashboard (and between projects). */
+export const editorSession: Accessor<EditorSession | null> = session;
+
+/** Set by the editor while a project is open; cleared on its way out. */
+export const setEditorSession = setSession;
+
+/** The session, or the failure a CLI caller can act on. */
+export function requireEditorSession(): EditorSession {
+ const current = session();
+ assert(current, "No project open — run `dapi open <dir>` first.");
+ return current;
+}
diff --git a/apps/web/src/context/dapi/shell.tsx b/apps/web/src/context/dapi/shell.tsx
deleted file mode 100644
index e820fa86..00000000
--- a/apps/web/src/context/dapi/shell.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-import { 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/reference/README.md b/reference/README.md
index 4476ce72..db7438b4 100644
--- a/reference/README.md
+++ b/reference/README.md
@@ -10,7 +10,7 @@ Each feature command has its own file (linked below). The JSX code syntax specif
| Group | Alias | Scope |
| ----- | ----- | ----- |
-| `media` | `m` | Inspect a media file by asset id or local path, without adding it to the project. |
+| `media` | `m` | Inspect a media file by path, without adding it to the project. Local files and URLs work with or without an open project; library paths need one. |
How the surface is divided:
diff --git a/reference/capture.md b/reference/capture.md
index 6bbc5073..2761bb79 100644
--- a/reference/capture.md
+++ b/reference/capture.md
@@ -39,4 +39,4 @@ A sheet's timecode is the span it covers; a single position's is its own. Sheets
## Errors
-Exits non-zero if the id is unknown, the id is ambiguous (two files use it — pass `file:id`), the id names an element inside a loop (capture its scene instead), the node has no timeline clock of its own (capture its scene instead), the node is not visible at any requested position, `--per-sheet` is outside 1 to 12, or a PNG can't be written.
+Exits non-zero if no project is open (`No project open` — run `dapi open <dir>` first), the id is unknown, the id is ambiguous (two files use it — pass `file:id`), the id names an element inside a loop (capture its scene instead), the node has no timeline clock of its own (capture its scene instead), the node is not visible at any requested position, `--per-sheet` is outside 1 to 12, or a PNG can't be written.
diff --git a/reference/context.md b/reference/context.md
index 19efeaee..faaaba8d 100644
--- a/reference/context.md
+++ b/reference/context.md
@@ -22,6 +22,10 @@ One JSON object:
}
```
+With no project open (the app sits at the dashboard) the report is just
+`{ project: null }`: there is no playhead, no world, and no fonts to speak of.
+Open one with [`dapi open`](./open.md).
+
`currentTime` is local to the active scene, the same origin a clip's `start`
and `end` are placed against, and in the same unit.
diff --git a/reference/media/filmstrip.md b/reference/media/filmstrip.md
index 1855871b..01180e14 100644
--- a/reference/media/filmstrip.md
+++ b/reference/media/filmstrip.md
@@ -1,4 +1,4 @@
-# `dapi media filmstrip <id|path>`
+# `dapi media filmstrip <path>`
Renders a **filmstrip** of a video to a PNG, written to a file in the system temp directory: a grid of frames sampled at even intervals across the window, each row stamped with a timestamp ruler. Video only; use [`dapi media waveform`](./waveform.md) to inspect the audio track. Renders locally; no credits. Alias: `film`.
@@ -6,7 +6,7 @@ Tick labels use `HH:MM:SS:FF` timecode (hours, minutes, seconds, frame within th
## Input
-- `<id|path>`: a video asset id, or a local video file to preview in place without adding it to the library (required).
+- `<path>`: a local video file to preview in place without adding it to the library, or a project library path (required; library paths need an open project).
- `-s, --start <time>`: start of the window to preview, a `Time` value in source/content time (optional; default `0`).
- `-e, --end <time>`: end of the window to preview, a `Time` value (optional; default the asset's duration).
- `-x, --scale <factor>`: scale factor for the thumbnails (optional; default `1`, clamped to `0.25`-`4`). The overall canvas size stays fixed, so smaller thumbnails fit **more rows and columns** (a denser grid sampling more moments) and larger thumbnails fit fewer but show more detail each.
@@ -24,4 +24,4 @@ One JSON object, the absolute path to the written PNG:
## Errors
-Exits non-zero if the id is unknown, the asset isn't a video, `--start`/`--end` fall outside the asset or cross (`--start` >= `--end`), `--scale` isn't a positive number, or `--output` can't be written.
+Exits non-zero if the path can't be resolved, the asset isn't a video, `--start`/`--end` fall outside the asset or cross (`--start` >= `--end`), `--scale` isn't a positive number, or `--output` can't be written.
diff --git a/reference/media/grab.md b/reference/media/grab.md
index 95f04e2d..5b735d26 100644
--- a/reference/media/grab.md
+++ b/reference/media/grab.md
@@ -1,10 +1,10 @@
-# `dapi media grab <id|path>`
+# `dapi media grab <path>`
Decodes one or more frames of a video asset at the given times and merges them into **contact sheets**: up to 12 frames per PNG, each cell labelled with its timecode and drawn as large as the sheet allows, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one. `--separate` writes a PNG per frame instead. Like [`capture`](../capture.md), but grabs the asset's own pixels (unlike `capture`, which renders the composited node). Renders locally; no credits. Past ~12 frames, [`media filmstrip`](./filmstrip.md) is the cheaper way to scan a clip.
## Input
-- `<id|path>`: a video asset id, or a local video file to grab frames from in place without adding it to the library (required).
+- `<path>`: a local video file to grab frames from in place without adding it to the library, or a project library path (required; library paths need an open project).
- `-t, --time <time...>`: one or more timestamps to grab, `Time` values in source/content time (optional; default `0`). A negative value is an offset back from the end of the clip, so `-1` is one second before the end and `-1f` one frame before it. Order is preserved in the output regardless of the order given. Mutually exclusive with `--count`.
- `-c, --count <n>`: instead of `--time`, grab `n` frames evenly spaced across the clip at a fixed interval of `window / n`, starting at the window start (optional; positive integer).
- `-s, --start <time>`: with `--count`, the start of the window to sample (optional; `Time` value; default `0`).
@@ -42,4 +42,4 @@ A sheet's timecode is the span it covers; a frame's is its own. Sheets come in t
## Errors
-Exits non-zero if the id is unknown, the asset is not a video, any `--time` is past the asset's duration, the `--count` window is empty, `--time` and `--count` are combined, `--start`/`--end` are given without `--count`, `--per-sheet` is outside 1 to 12, more than 100 frames are requested without `--uncapped`, or a PNG can't be written.
+Exits non-zero if the path can't be resolved, the asset is not a video, any `--time` is past the asset's duration, the `--count` window is empty, `--time` and `--count` are combined, `--start`/`--end` are given without `--count`, `--per-sheet` is outside 1 to 12, more than 100 frames are requested without `--uncapped`, or a PNG can't be written.
diff --git a/reference/media/listen.md b/reference/media/listen.md
index 08bb0fb6..3fdfbde6 100644
--- a/reference/media/listen.md
+++ b/reference/media/listen.md
@@ -1,10 +1,10 @@
-# `dapi media listen <id|path>`
+# `dapi media listen <path>`
Puts a multimodal model in front of an audio track and returns its answer. With no prompt it returns a general description of what is heard; with `--prompt` it answers that question about the audio (e.g. "who is speaking?", "what music is playing?", "summarize what is said"). Accepts an audio file or a video, but only the audio track is analyzed by default. Alias: `watch`.
## Input
-- `<id|path>`: an audio or video asset id, or a local file to analyze in place without adding it to the library (required).
+- `<path>`: a local audio or video file to analyze in place without adding it to the library, or a project library path (required; library paths need an open project).
- `-p, --prompt <str>`: question or instruction about the audio (optional; defaults to a general description).
- `-s, --start <time>`: start of the segment to analyze, a `Time` value (optional; default `0`). Timestamps in the analysis are relative to this point.
- `-e, --end <time>`: end of the segment to analyze, a `Time` value (optional; default the asset's duration).
@@ -20,4 +20,4 @@ One JSON object, the model's answer. `start`/`end` echo the analyzed window (in
## Errors
-Exits non-zero if the id is unknown, the asset isn't a video or audio asset, or `--start`/`--end` cross (`--start` >= `--end`).
+Exits non-zero if the path can't be resolved, the asset isn't a video or audio asset, or `--start`/`--end` cross (`--start` >= `--end`).
diff --git a/reference/media/probe.md b/reference/media/probe.md
index 7bd30247..a1740961 100644
--- a/reference/media/probe.md
+++ b/reference/media/probe.md
@@ -1,10 +1,10 @@
-# `dapi media probe <id|path>`
+# `dapi media probe <path>`
Reads the container and per-track technical metadata of an asset; like `ffprobe`, but demuxed locally with mediabunny. Reports the container format, duration, metadata tags, and every track's codec parameters without decoding any media. Reads locally; no credits.
## Input
-- `<id|path>`: an asset id, or a local file to probe in place without adding it to the library (required). Any asset type is accepted.
+- `<path>`: a local file to probe in place without adding it to the library, or a project library path (required; library paths need an open project). Any asset type is accepted.
## Output
@@ -12,4 +12,4 @@ One JSON object. The shape is **not yet stable**: it reports whatever mediabunny
## Errors
-Exits non-zero if the id is unknown.
+Exits non-zero if the path can't be resolved.
diff --git a/reference/media/transcribe.md b/reference/media/transcribe.md
index 5b1655b2..ae5e29ff 100644
--- a/reference/media/transcribe.md
+++ b/reference/media/transcribe.md
@@ -1,12 +1,12 @@
-# `dapi media transcribe <id|path>`
+# `dapi media transcribe <path>`
Transcribes the speech in a video or audio asset and returns the timed transcript. Word-level start/end times are in **seconds** (source/content time).
## Input
-- `<id|path>`: a video or audio asset id, or a local file to transcribe in place without adding it to the library (required).
+- `<path>`: a local video or audio file to transcribe in place without adding it to the library, or a project library path (required; library paths need an open project).
-The whole asset is transcribed once per app session (cached in memory, keyed by file content, for ids and paths alike; an app restart or an edited file re-transcribes).
+The whole asset is transcribed once per app session (cached in memory, keyed by file content; an app restart or an edited file re-transcribes).
## Output
@@ -23,4 +23,4 @@ One JSON object, the transcript:
## Errors
-Exits non-zero if the id is unknown or the asset is not a video/audio asset, or if no speech is detected in the audio at all (`No speech detected`).
+Exits non-zero if the path can't be resolved or the asset is not a video/audio asset, or if no speech is detected in the audio at all (`No speech detected`).
diff --git a/reference/media/waveform.md b/reference/media/waveform.md
index d4e3b9d8..7d7ef2db 100644
--- a/reference/media/waveform.md
+++ b/reference/media/waveform.md
@@ -1,4 +1,4 @@
-# `dapi media waveform <id|path>`
+# `dapi media waveform <path>`
Renders the audio track of a video or audio file as an amplitude **waveform** PNG, written to a file in the system temp directory: loudness over time drawn from decoded audio peaks, with a timestamp ruler. Silent stretches are highlighted in red. Renders locally; no credits. Alias: `wave`.
@@ -6,7 +6,7 @@ Tick labels use `HH:MM:SS:FF` timecode (hours, minutes, seconds, frame within th
## Input
-- `<id|path>`: a video or audio asset id, or a local file to preview in place without adding it to the library (required).
+- `<path>`: a local video or audio file to preview in place without adding it to the library, or a project library path (required; library paths need an open project).
- `-s, --start <time>`: start of the window to preview, a `Time` value in source/content time (optional; default `0`).
- `-e, --end <time>`: end of the window to preview, a `Time` value (optional; default the asset's duration).
- `-x, --scale <factor>`: scale factor for the waveform (optional; default `1`, clamped to `0.25`-`4`). The overall canvas size stays fixed, so a smaller scale fits **more rows and columns** (a denser time axis) and a larger scale fits fewer but taller rows.
@@ -25,4 +25,4 @@ One JSON object, the absolute path to the written PNG plus the silent stretches
## Errors
-Exits non-zero if the id is unknown, the asset has no decodable audio track, `--start`/`--end` fall outside the asset or cross (`--start` >= `--end`), `--scale` isn't a positive number, or `--output` can't be written.
+Exits non-zero if the path can't be resolved, the asset has no decodable audio track, `--start`/`--end` fall outside the asset or cross (`--start` >= `--end`), `--scale` isn't a positive number, or `--output` can't be written.