The VS Code of video editing, built for agents.
TypeScript
Add 'report' command to CLI for bug reporting with diagnostics
konstantin-paulus97ef63115fbd
diff --git a/README.md b/README.mdindex 59438ee4..889445e1 100644--- a/README.md+++ b/README.md@@ -113,7 +113,7 @@ Everything a mount produces stays a first-class editor node, so a person can pic## Seeing and hearing the media-Cutting footage requires looking at it. The CLI ships the inspection tools an agent needs to work with media it cannot watch:+Cutting footage requires understanding it. The CLI ships the inspection tools an agent needs to work with media it cannot watch:```shdapi media probe clip.mp4 # container + codec metadata, like ffprobe@@ -140,6 +140,7 @@ dapi node capture # see the canvas itself| `dapi screenshot` / `dapi logs` | The app itself: capture the window, read recent console output || `dapi fetch` | Download a video from yt/tt/ig, ready for `dapi asset add` || `dapi whoami` | The authenticated account |+| `dapi report` | Report a bug in the CLI or the app: diagnostics bundled, prefilled GitHub issue link |Conventions throughout: single results are one JSON value, collections are JSON Lines, errors go to stderr with exit code `1`. Everything is built to be piped, grepped, and driven by a program.diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex fc72f6aa..459bb25c 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -14,9 +14,10 @@ import { parseTime, TIME_FPS } from "@diffusionstudio/jsx";import { editor, errnoCode, waitForCliSocket, GENERATE_TIMEOUT_MS } from "./cli-client";import { compileProject } from "./compile-project";import { listLocalFonts } from "./fonts";+import { buildIssueReport } from "./report";import { openFolder } from "./open-folder";import { fetchVideo } from "./ytdlp";-import type { AssetRef, EncoderConfigInput, FrameQuality, LogLevel, NodePatch } from "./protocol";+import type { AssetRef, EncoderConfigInput, FrameQuality, LogEntry, LogLevel, NodePatch } from "./protocol";// Long-running commands (renders, AI generation) override the default 60s.const GENERATE = { context: { timeoutMs: GENERATE_TIMEOUT_MS } };@@ -100,6 +101,17 @@ async function openTarget(target: string | undefined, background: boolean): PromopenApp(target, background);}+function openInBrowser(url: string): void {+ const os = platform();+ if (os === "darwin") {+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();+ } else if (os === "win32") {+ spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore" }).unref();+ } else {+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();+ }+}+function handleSocketError(e: unknown): never {const code = errnoCode(e);if (code === "ENOENT" || code === "ECONNREFUSED") {@@ -965,18 +977,20 @@ async function showLogs(opts: LogsOptions): Promise<void> {try {const entries = await editor.logs.query({ tail, level: opts.level as LogLevel | undefined });- const pad = (n: number, w = 2) => String(n).padStart(w, "0");- for (const entry of entries) {- const d = new Date(entry.ts);- const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;- const source = entry.source ? ` (${entry.source})` : "";- console.log(`${time} [${entry.level}] ${entry.message}${source}`);- }+ for (const entry of entries) console.log(formatLogEntry(entry));} catch (e) {handleSocketError(e);}}+function formatLogEntry(entry: LogEntry): string {+ const pad = (n: number, w = 2) => String(n).padStart(w, "0");+ const d = new Date(entry.ts);+ const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;+ const source = entry.source ? ` (${entry.source})` : "";+ return `${time} [${entry.level}] ${entry.message}${source}`;+}+type ScreenshotOptions = { output?: string };async function appScreenshot(opts: ScreenshotOptions): Promise<void> {@@ -992,6 +1006,81 @@ async function appScreenshot(opts: ScreenshotOptions): Promise<void> {}}+type IssueOptions = { body?: string; command?: string[]; logs?: string; output?: string; open?: boolean };++const ISSUE_LOG_TAIL = 50;++async function reportIssue(title: string, opts: IssueOptions): Promise<void> {+ const summary = title.trim();+ if (!summary) {+ console.error("A one-line title is required.");+ process.exit(1);+ }++ let tail = ISSUE_LOG_TAIL;+ if (opts.logs !== undefined) {+ const n = Number(opts.logs);+ if (!Number.isInteger(n) || n < 0) {+ console.error(`--logs must be a non-negative integer (got "${opts.logs}")`);+ process.exit(1);+ }+ tail = n;+ }++ // The app being broken (or down) is exactly what gets reported, so a failed+ // log read is recorded in the report rather than failing the command.+ let logs: string[] | undefined;+ let appStatus = "not checked";+ if (tail > 0) {+ try {+ logs = (await editor.logs.query({ tail })).map(formatLogEntry);+ appStatus = "running";+ } catch (e) {+ const code = errnoCode(e);+ appStatus = code === "ENOENT" || code === "ECONNREFUSED"+ ? "not running"+ : `unreachable (${(e as Error).message})`;+ }+ }++ const slug = summary.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-|-$/g, "");+ const filename = `dapi-report-${slug || "untitled"}-${randomUUID().slice(0, 8)}.md`;++ let path: string;+ let dir: string;+ if (opts.output === undefined) {+ dir = tmpdir();+ path = join(dir, filename);+ } else {+ const output = isAbsolute(opts.output) ? opts.output : resolve(process.cwd(), opts.output);+ // A trailing separator always means a directory, as does an existing one.+ const isDir = /[\\/]$/.test(opts.output) || (existsSync(output) && statSync(output).isDirectory());+ dir = isDir ? output : dirname(output);+ path = isDir ? join(output, filename) : output;+ }++ const { markdown, url, truncated } = buildIssueReport({+ title: summary,+ body: opts.body,+ commands: opts.command,+ logs,+ appStatus,+ version,+ reportPath: path,+ });++ try {+ mkdirSync(dir, { recursive: true });+ writeFileSync(path, markdown);+ } catch (e) {+ console.error(`Could not write the report to ${path}: ${(e as Error).message}`);+ process.exit(1);+ }++ if (opts.open) openInBrowser(url);+ console.log(JSON.stringify({ path, url, truncated }));+}+function startSpinner(label: string): () => void {if (!process.stderr.isTTY) {process.stderr.write(`${label}…\n`);@@ -1502,6 +1591,20 @@ program.option("-o, --output <dir>", "directory to write the PNG into (default: system temp dir)").action((opts: ScreenshotOptions) => appScreenshot(opts));+program+ .command("report")+ .alias("issue")+ .description(+ `Report a bug in dapi or the app itself. Writes a markdown report with diagnostics attached (dapi version, platform, recent app logs) and prints a prefilled GitHub issue URL; nothing is submitted, a human reviews and opens it.`,+ )+ .argument("<title>", "one-line summary of the problem")+ .option("-b, --body <text>", "what happened, in markdown: expected vs actual, and anything the diagnostics won't show")+ .option("-c, --command <cmd...>", "the dapi command(s) that reproduce it, in order; repeatable")+ .option("--logs <n>", `trailing app log entries to attach (0 to omit; default: ${ISSUE_LOG_TAIL})`)+ .option("-o, --output <path>", "file path, or directory to write the report into (default: system temp dir)")+ .option("--open", "open the prefilled GitHub issue page in the default browser")+ .action((title: string, opts: IssueOptions) => reportIssue(title, opts));+program.command("fonts").description(diff --git a/apps/cli/src/report.ts b/apps/cli/src/report.tsnew file mode 100644index 00000000..a2960ac0--- /dev/null+++ b/apps/cli/src/report.ts@@ -0,0 +1,79 @@+/* 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 { arch, platform, release } from "node:os";++const ISSUE_URL = "https://github.com/diffusionstudio/editor/issues/new";++// GitHub answers a prefilled issue URL with 414 well before the 8 KB mark, so+// the link carries a trimmed body and points at the full report on disk.+const MAX_URL_LENGTH = 6000;++export type IssueInput = {+ title: string;+ body?: string;+ commands?: string[];+ logs?: string[]; // already formatted log lines, oldest first+ appStatus: string; // "running", "not running", "not checked", or why it was unreachable+ version: string;+ reportPath: string; // where the full report is written; referenced when the URL is truncated+};++export type IssueReport = { markdown: string; url: string; truncated: boolean };++function fence(language: string, content: string): string {+ return `\`\`\`${language}\n${content}\n\`\`\``;+}++function environmentTable(input: IssueInput): string {+ const rows: Array<[string, string]> = [+ ["dapi", input.version],+ ["platform", `${platform()} ${release()} (${arch()})`],+ ["node", process.version],+ ["app", input.appStatus],+ ];+ return ["| | |", "| --- | --- |", ...rows.map(([k, v]) => `| ${k} | ${v} |`)].join("\n");+}++// encodeURIComponent throws on a lone surrogate, which slicing the body mid+// emoji can produce; dropping the orphan half is enough to keep the search safe.+function encodedLength(text: string): number {+ const code = text.charCodeAt(text.length - 1);+ const safe = code >= 0xd800 && code <= 0xdbff ? text.slice(0, -1) : text;+ return encodeURIComponent(safe).length;+}++function issueUrl(title: string, body: string, reportPath: string): { url: string; truncated: boolean } {+ const base = `${ISSUE_URL}?title=${encodeURIComponent(title)}&body=`;+ const room = MAX_URL_LENGTH - base.length;+ if (encodedLength(body) <= room) return { url: base + encodeURIComponent(body), truncated: false };++ const note = `\n\n_Truncated for the link — full report: ${reportPath}_\n`;+ const budget = room - encodedLength(note);++ // Longest prefix of the body that still fits, by binary search on characters:+ // percent-encoding is per-character, so the encoded length grows monotonically.+ let lo = 0;+ let hi = body.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (encodedLength(body.slice(0, mid)) <= budget) lo = mid;+ else hi = mid - 1;+ }+ return { url: base + encodeURIComponent(body.slice(0, lo) + note), truncated: true };+}++export function buildIssueReport(input: IssueInput): IssueReport {+ const sections: string[] = [];++ if (input.body?.trim()) sections.push(input.body.trim());+ if (input.commands?.length) sections.push(`## Repro\n\n${fence("sh", input.commands.join("\n"))}`);+ sections.push(`## Environment\n\n${environmentTable(input)}`);+ if (input.logs?.length) sections.push(`## App logs\n\n${fence("", input.logs.join("\n"))}`);++ const body = sections.join("\n\n");+ const { url, truncated } = issueUrl(input.title, body, input.reportPath);++ return { markdown: `# ${input.title}\n\n${body}\n`, url, truncated };+}diff --git a/reference/README.md b/reference/README.mdindex 10c7a765..9c1b78ed 100644--- a/reference/README.md+++ b/reference/README.md@@ -6,7 +6,7 @@ Each feature command has its own file (linked below). The JSX code syntax consum## Groups-**Top-level:** [`open`](./open.md), [`whoami`](./whoami.md), [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`context`](./context.md) (alias `ctx`), [`mount`](./mount.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md), [`fetch`](./fetch.md).+**Top-level:** [`open`](./open.md), [`whoami`](./whoami.md), [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`report`](./report.md), [`context`](./context.md) (alias `ctx`), [`mount`](./mount.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md), [`fetch`](./fetch.md).| Group | Alias | Scope || ----- | ----- | ----- |@@ -32,6 +32,7 @@ How the surface is divided:- [`dapi whoami`](./whoami.md): print the authenticated account- [`dapi logs`](./logs.md): recent console output from the running app- [`dapi screenshot`](./screenshot.md): capture the entire application window as a PNG+- [`dapi report`](./report.md): file a bug report about the CLI or the app, with diagnostics attached### Document@@ -122,4 +123,4 @@ Time inputs take the `Time` format unless noted otherwise. Times in **outputs**- **Unix-style names are canonical:** list/read is `ls`, delete is `rm`, duplicate is `cp`, move/reparent is `mv`, search is `grep`. The longer English forms (`list`, `remove`, `duplicate`, `move`) are aliases of the Unix forms, not the other way around. `get` is a universal alias for `ls`. Commands without a natural Unix equivalent (`tree`, `rename`, `patch`, `add`, `create`, `active`, `context`, `whoami`, `open`, `focus`, `set`) keep their descriptive names.- **Stderr:** human-readable error messages.- **Exit codes:** `0` on success, `1` on any error (missing file, app not running, invalid input, IPC error).-- **App must be running:** every command except `open`, `fonts`, and `fetch` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`.+- **App must be running:** every command except `open`, `fonts`, and `fetch` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`. `report` is the one command that reads from the app but tolerates its absence, recording it in the report instead of failing.diff --git a/reference/report.md b/reference/report.mdnew file mode 100644index 00000000..59d37e2e--- /dev/null+++ b/reference/report.md@@ -0,0 +1,72 @@+# `dapi report <title>`++Reports a bug in `dapi` itself or in the app behind it: a command that errors, contradicts this reference, or returns something it shouldn't. Bundles the description with diagnostics (dapi version, platform, node version, the app's recent console output) into a markdown report on disk, and prints a prefilled GitHub issue URL for [diffusionstudio/editor](https://github.com/diffusionstudio/editor/issues).++Nothing is submitted. The command only writes a file and composes a link; a human reviews the report and opens the issue, either from the printed URL or by pasting the file. `--open` opens the prefilled page in the default browser.++This is for defects in the tooling, not for problems inside a project: a composition that looks wrong, a node in the wrong place, or a generation that missed the prompt are editing problems, fixed with `node patch` / `mount`, not reported here.++Does not require the app to be running. If the app is down or unreachable, the report records that instead of failing, since that is often the bug being reported.++## Arguments++- `<title>`: one-line summary of the problem, used as the issue title and in the report filename.++## Options++- `-b, --body <text>`: what happened, in markdown: what you expected, what you got, and anything the diagnostics won't show.+- `-c, --command <cmd...>`: the `dapi` command(s) that reproduce it, in order. Repeatable (`-c "dapi node ls 5" -c "dapi node capture 5"`); rendered as a shell block under `## Repro`.+- `--logs <n>`: trailing app log entries to attach (default: 50). `--logs 0` omits the section, and then the app is not contacted at all.+- `-o, --output <path>`: where to write the report. A directory when it exists as one or ends with a path separator (the file is named after the title); otherwise an exact file path. Default: the system temp directory.+- `--open`: open the prefilled GitHub issue page in the default browser.++## Output++One JSON object:++```ts+{+ path: string, // absolute path of the markdown report+ url: string, // prefilled github.com/diffusionstudio/editor/issues/new link+ truncated: boolean // true when the body was too long for the URL and was cut short in the link only+}+```++The report on disk is always complete. Long reports exceed what a prefilled URL can carry, so the link's body is trimmed and ends with a pointer to `path`; `truncated` says when that happened.++## Report layout++````md+# <title>++<body>++## Repro++```sh+dapi node capture 42+```++## Environment++| | |+| --- | --- |+| dapi | 0.129.0 |+| platform | darwin 25.5.0 (arm64) |+| node | v20.19.0 |+| app | running |++## App logs++```+19:37:17.538 [info] Finalizing file (…)+```+````++The `app` row reads `running`, `not running`, `not checked` (with `--logs 0`), or the reason it was unreachable.++## Notes++- Attached logs are the same entries [`logs`](./logs.md) prints, and can contain project names, file paths, and prompt text. They land in a local file, not on GitHub, until someone submits the report: review it before posting.+- Exits non-zero on an empty title, an invalid `--logs`, or an unwritable `--output`.+- `dapi issue` is an alias of this command.