Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add logging functionality to CLI and desktop applications

konstantin-paulus7f1e8f7a0f87
diff --git a/apps/cli/src/cli-channels.ts b/apps/cli/src/cli-channels.ts
index e390b66f..3539d248 100644
--- a/apps/cli/src/cli-channels.ts
+++ b/apps/cli/src/cli-channels.ts
@@ -175,3 +175,9 @@ export type ProjectSummary = {
lastAccessedAt: string;
};
+export type LogLevel = "debug" | "info" | "warning" | "error";
+
+export type LogEntry = { ts: number; level: LogLevel; message: string; source: string };
+
+export type LogsRequest = { tail?: number; level?: LogLevel };
+
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 378de0c3..e9a2fa90 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -16,7 +16,7 @@ import { compileProject } from "./compile-project";
import { listLocalFonts } from "./fonts";
import { openFolder } from "./open-folder";
import { fetchVideo } from "./ytdlp";
-import type { AssetRef, EncoderConfigInput, FrameQuality, NodePatch } from "./protocol";
+import type { AssetRef, EncoderConfigInput, FrameQuality, LogLevel, NodePatch } from "./protocol";
// Long-running commands (renders, AI generation) override the default 60s.
const GENERATE = { context: { timeoutMs: GENERATE_TIMEOUT_MS } };
@@ -953,6 +953,39 @@ async function whoami(): Promise<void> {
}
}
+const LOG_LEVELS = ["debug", "info", "warning", "error"] as const;
+
+type LogsOptions = { tail?: string; level?: string };
+
+async function showLogs(opts: LogsOptions): Promise<void> {
+ if (opts.level !== undefined && !LOG_LEVELS.includes(opts.level as LogLevel)) {
+ console.error(`--level must be one of ${LOG_LEVELS.join(", ")} (got "${opts.level}")`);
+ process.exit(1);
+ }
+ let tail: number | undefined;
+ if (opts.tail !== undefined) {
+ const n = Number(opts.tail);
+ if (!Number.isInteger(n) || n <= 0) {
+ console.error(`--tail must be a positive integer (got "${opts.tail}")`);
+ process.exit(1);
+ }
+ tail = n;
+ }
+
+ 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}`);
+ }
+ } catch (e) {
+ handleSocketError(e);
+ }
+}
+
function startSpinner(label: string): () => void {
if (!process.stderr.isTTY) {
process.stderr.write(`${label}…\n`);
@@ -1448,6 +1481,15 @@ program
.description(`Print the authenticated account, or null if signed out.`)
.action(() => whoami());
+program
+ .command("logs")
+ .description(
+ `Print recent console output from the running app (what the devtools console shows: page logs, worker logs, uncaught errors), oldest first, one line per entry: local time, level, message, source location. The app buffers the last 2000 entries across reloads and project switches, so this replaces relaunching with ELECTRON_ENABLE_LOGGING=1 when debugging renderer-side behavior.`,
+ )
+ .option("-n, --tail <n>", "output only the last <n> entries")
+ .option("-l, --level <level>", `minimum level to include: "debug", "info", "warning", or "error"`)
+ .action((opts: LogsOptions) => showLogs(opts));
+
program
.command("fonts")
.description(
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index cd193c6f..660408de 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -9,6 +9,8 @@
//
// CLI traffic uses a separate wire pair (CLI_WIRE in @diffusionstudio/cli/protocol);
// main forwards it opaquely without inspecting channel names.
+import type { LogEntry } from "@diffusionstudio/cli/protocol";
+
export const MAIN_WIRE = {
REQUEST: "main:request",
RESPONSE: "main:response",
@@ -33,6 +35,7 @@ export const MAIN_CHANNELS = {
FILE_WRITE_CLOSE: "file:write-close",
FILE_WRITE_ABORT: "file:write-abort",
HEADLESS_GET_MODE: "headless:get-mode",
+ LOGS_GET: "logs:get",
// Main→Renderer events
AUTH_CALLBACK: "auth:callback",
@@ -67,6 +70,7 @@ export type MainRequestMap = {
response: void;
};
[MAIN_CHANNELS.HEADLESS_GET_MODE]: { request: void; response: boolean };
+ [MAIN_CHANNELS.LOGS_GET]: { request: void; response: LogEntry[] };
};
export type MainRequestChannel = keyof MainRequestMap;
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index a3ab9794..3f1e33ef 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -12,6 +12,7 @@ import { startCliServer, stopCliServer, isHeadless } from "./cli-server";
import { setupAppMenu } from "./menu";
import { mainBridge } from "./main-manager";
import { MAIN_CHANNELS } from "./main-channels";
+import type { LogEntry } from "@diffusionstudio/cli/protocol";
const DEV_URL = "http://localhost:5173";
const AUTH_PROTOCOL = "diffusion";
@@ -53,6 +54,29 @@ const openWrites = new Map<string, { handle: FileHandle; path: string }>();
let mainWindow: BrowserWindow | null = null;
let pendingAuthUrl: string | null = null;
+// Renderer console mirror, served to the CLI via LOGS_GET. Lives in main so
+// it survives reloads and captures everything the devtools console shows
+// (page logs, worker logs, uncaught errors) without touching the web bundle.
+const LOG_BUFFER_MAX = 2000;
+const logBuffer: LogEntry[] = [];
+
+function pushLog(level: LogEntry["level"], message: string, source: string) {
+ logBuffer.push({ ts: Date.now(), level, message, source });
+ if (logBuffer.length > LOG_BUFFER_MAX) logBuffer.shift();
+}
+
+function captureConsole(window: BrowserWindow) {
+ window.webContents.on("console-message", ({ level, message, lineNumber, sourceId }) => {
+ pushLog(level, message, sourceId ? `${sourceId}:${lineNumber}` : "");
+ });
+ window.webContents.on("preload-error", (_event, path, error) => {
+ pushLog("error", `Preload error: ${error.message}`, path);
+ });
+ window.webContents.on("render-process-gone", (_event, details) => {
+ pushLog("error", `Renderer process gone: ${details.reason} (exit code ${details.exitCode})`, "");
+ });
+}
+
function findProtocolUrl(argv: string[]): string | null {
return argv.find((arg) => arg.startsWith(`${AUTH_PROTOCOL}://`)) ?? null;
}
@@ -103,6 +127,8 @@ function createWindow(show = true) {
},
});
+ captureConsole(mainWindow);
+
mainWindow.webContents.on("did-finish-load", () => {
if (pendingAuthUrl) {
mainBridge.emit(mainWindow, MAIN_CHANNELS.AUTH_CALLBACK, { url: pendingAuthUrl });
@@ -183,6 +209,7 @@ if (app.requestSingleInstanceLock()) {
});
mainBridge.handle(MAIN_CHANNELS.WINDOW_IS_FULLSCREEN, () => mainWindow?.isFullScreen() ?? false);
mainBridge.handle(MAIN_CHANNELS.HEADLESS_GET_MODE, () => isHeadless());
+ mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);
mainBridge.handle(MAIN_CHANNELS.FILE_TRANSFER, ({ selector, absolutePath }) =>
setFileInputFiles(selector, absolutePath),
);
diff --git a/apps/web/src/context/editor-api/api.tsx b/apps/web/src/context/editor-api/api.tsx
index c2cdd73f..c7e8b353 100644
--- a/apps/web/src/context/editor-api/api.tsx
+++ b/apps/web/src/context/editor-api/api.tsx
@@ -15,6 +15,7 @@ import { handleSelectionFocus, handleSelectionList, handleSelectionSet } from ".
import { handleNodeList, handleNodeTree, handleNodeGrep, handleNodeCapture, handleNodeDelete, handleNodePatch, handleNodeDuplicate, handleNodeRender } from "./node";
import { handleMount, handleNodeInsert } from "./mount";
import { handleProjectActive, handleProjectList, handleProjectCreate, handleProjectDelete, handleProjectOpen } from "./project";
+import { handleLogs } from "./logs";
import { handleModels } from "./models";
import { handleVoices } from "./voices";
import { cliBridge, mainBridge } from '@/lib/ipc';
@@ -99,6 +100,7 @@ function createAppRouter({ getEngine, getUser, requireAuth, setParams }: AppRout
context: q0(handleContextGet(getEngine)),
mount: m(handleMount(getEngine)),
models: q(handleModels()),
+ logs: q(handleLogs()),
voices: q0(handleVoices()),
asset: t.router({
add: m(handleAssetsAdd(getEngine)),
diff --git a/apps/web/src/context/editor-api/logs.ts b/apps/web/src/context/editor-api/logs.ts
new file mode 100644
index 00000000..e70d29e5
--- /dev/null
+++ b/apps/web/src/context/editor-api/logs.ts
@@ -0,0 +1,21 @@
+/* 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 { mainBridge } from "@/lib/ipc";
+import { MAIN_CHANNELS } from "@desktop/main-channels";
+import type { LogsRequest, LogLevel } from "@diffusionstudio/cli/channels";
+
+const LEVEL_RANK: Record<LogLevel, number> = { debug: 0, info: 1, warning: 2, error: 3 };
+
+export function handleLogs() {
+ return async (req: LogsRequest) => {
+ let entries = await mainBridge.call(MAIN_CHANNELS.LOGS_GET, undefined);
+ if (req.level !== undefined) {
+ const min = LEVEL_RANK[req.level];
+ entries = entries.filter((e) => LEVEL_RANK[e.level] >= min);
+ }
+ if (req.tail !== undefined) entries = entries.slice(-req.tail);
+ return entries;
+ };
+}