Skip to content

The VS Code of video editing, built for agents.

TypeScript

Update CLI and Electron integration with tRPC and WebSocket enhancements

konstantin-paulus65794909785c
diff --git a/apps/cli/package.json b/apps/cli/package.json
index c4ca66f5..53799876 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -11,21 +11,25 @@
"./channels": "./src/cli-channels.ts"
},
"scripts": {
- "build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/index.js && chmod +x dist/index.js",
+ "build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --external:bufferutil --external:utf-8-validate --outfile=dist/index.js && chmod +x dist/index.js",
"check": "tsc --noEmit",
"symlink:remove": "rm -f /opt/homebrew/bin/dapi",
"symlink:create": "npm run build && ln -sf \"$PWD/dist/index.js\" /opt/homebrew/bin/dapi"
},
"dependencies": {
"@babel/core": "^7.29.7",
+ "@trpc/client": "^11.18.0",
+ "@trpc/server": "^11.18.0",
"@babel/preset-typescript": "^7.27.1",
"babel-preset-solid": "^1.9.12",
"commander": "^14.0.3",
- "esbuild": "^0.28.1"
+ "esbuild": "^0.28.1",
+ "ws": "^8.18.3"
},
"devDependencies": {
"@types/babel__core": "^7.20.5",
"@types/node": "^24.10.1",
+ "@types/ws": "^8.18.1",
"typescript": "~5.9.3"
}
}
diff --git a/apps/cli/src/cli-channels.ts b/apps/cli/src/cli-channels.ts
index 399344e0..3f595774 100644
--- a/apps/cli/src/cli-channels.ts
+++ b/apps/cli/src/cli-channels.ts
@@ -4,60 +4,33 @@
import type { PatchProps } from "@diffusionstudio/jsx";
-// Wire-level channels for the CLI-forwarding path. Main only knows these two —
-// it does not inspect logical channel names. The renderer mirrors requests
-// back onto FORWARD_REPLY, correlated by envelope id.
+// Wire-level channel for the CLI handshake. Each CLI command hosts a
+// short-lived WebSocket server; main's only job is to relay the connect
+// info to the renderer, which then dials the CLI directly. Main never sees
+// request payloads.
export const CLI_WIRE = {
- FORWARD_REQ: "cli:fwd:req",
- FORWARD_REPLY: "cli:fwd:reply",
+ CONNECT: "cli:connect",
} as const;
-// Logical channels — known only to the CLI and renderer. `cli:ping` is a
-// built-in: the renderer's bridge auto-registers it so `waitForCliSocket`
-// can probe end-to-end without depending on an app-level handler.
-export const CLI_CHANNELS = {
- PING: "cli:ping",
- CONTEXT: "cli:context",
- ASSETS_ADD: "cli:assets:add",
- ASSETS_LIST: "cli:assets:list",
- ASSET_TREE: "cli:asset:tree",
- ASSETS_DELETE: "cli:assets:delete",
- ASSETS_MOVE: "cli:assets:move",
- ASSETS_EXPORT: "cli:assets:export",
- FOLDERS_LIST: "cli:folders:list",
- FOLDER_CREATE: "cli:folder:create",
- FOLDER_RENAME: "cli:folder:rename",
- FOLDERS_MOVE: "cli:folders:move",
- FOLDERS_DELETE: "cli:folders:delete",
- ASSET_PROBE: "cli:asset:probe",
- ASSET_FRAME: "cli:asset:frame",
- ASSET_TRANSCRIBE: "cli:asset:transcribe",
- ASSET_VISUALIZE: "cli:asset:visualize",
- ASSET_ANALYZE: "cli:asset:analyze",
- SELECTION_LIST: "cli:selection:list",
- SELECTION_SET: "cli:selection:set",
- SELECTION_FOCUS: "cli:selection:focus",
- NODE_LIST: "cli:node:list",
- NODE_TREE: "cli:node:tree",
- NODE_GREP: "cli:node:grep",
- NODE_SCREENSHOT: "cli:node:screenshot",
- MOUNT: "cli:mount",
- NODE_INSERT: "cli:node:insert",
- NODE_DELETE: "cli:node:delete",
- NODE_PATCH: "cli:node:patch",
- NODE_DUPLICATE: "cli:node:duplicate",
- NODE_RENDER: "cli:node:render",
- PROJECT_ACTIVE: "cli:project:active",
- PROJECT_LIST: "cli:project:list",
- PROJECT_CREATE: "cli:project:create",
- PROJECT_DELETE: "cli:project:delete",
- PROJECT_OPEN: "cli:project:open",
- MODELS: "cli:models",
- VOICES: "cli:voices",
- WHOAMI: "cli:whoami",
-} as const;
+// Sent by the CLI to main over the unix socket, relayed verbatim to the
+// renderer. The token guards the loopback WebSocket server against other
+// local processes racing to connect first.
+export type CliHandshake = { port: number; token: string };
+
+export type CliHandshakeReply = { ok: true } | { ok: false; error: string };
+
+// One tRPC request/reply pair per WebSocket connection. `path` is the
+// dot-joined procedure path in the renderer's router (e.g. "asset.frame");
+// procedure inputs and outputs are typed end-to-end via the AppRouter type,
+// so the wire envelope stays untyped.
+export type CliRequest = {
+ path: string;
+ input: unknown;
+};
-export type CliChannel = (typeof CLI_CHANNELS)[keyof typeof CLI_CHANNELS];
+export type CliReply =
+ | { ok: true; data: unknown }
+ | { ok: false; error: string };
export type NodeRef = { id: number; name: string; type: string };
@@ -212,158 +185,3 @@ export type ProjectSummary = {
lastAccessedAt: string;
};
-export type CliRequestMap = {
- [CLI_CHANNELS.PING]: { request: void; response: void };
- [CLI_CHANNELS.CONTEXT]: { request: void; response: any };
- [CLI_CHANNELS.ASSETS_ADD]: {
- request: { paths: string[]; folderId?: string };
- response: any;
- };
- [CLI_CHANNELS.ASSETS_LIST]: {
- request: { ids?: string[] };
- response: AssetListResult[];
- };
- [CLI_CHANNELS.ASSET_TREE]: {
- request: { folderId?: string; depth?: number };
- response: AssetTreeEntry[];
- };
- [CLI_CHANNELS.ASSETS_DELETE]: { request: { ids: string[] }; response: any };
- [CLI_CHANNELS.ASSETS_MOVE]: {
- request: { ids: string[]; to?: string };
- response: AssetMoveResult[];
- };
- [CLI_CHANNELS.ASSETS_EXPORT]: {
- request: AssetsExportRequest;
- response: AssetExportResult[];
- };
- [CLI_CHANNELS.FOLDERS_LIST]: {
- request: { parentId?: string };
- response: FolderInfo[];
- };
- [CLI_CHANNELS.FOLDER_CREATE]: {
- request: { name: string; parentId?: string };
- response: FolderInfo;
- };
- [CLI_CHANNELS.FOLDER_RENAME]: {
- request: { id: string; name: string };
- response: FolderInfo;
- };
- [CLI_CHANNELS.FOLDERS_MOVE]: {
- request: { ids: string[]; to?: string };
- response: FolderMoveResult[];
- };
- [CLI_CHANNELS.FOLDERS_DELETE]: {
- request: { ids: string[] };
- response: FolderDeleteResult[];
- };
- [CLI_CHANNELS.ASSET_PROBE]: {
- request: AssetProbeRequest;
- response: unknown;
- };
- [CLI_CHANNELS.ASSET_FRAME]: {
- request: AssetFrameRequest;
- response: AssetFrameResult;
- };
- [CLI_CHANNELS.ASSET_TRANSCRIBE]: {
- request: AssetTranscribeRequest;
- response: AssetTranscribeResult;
- };
- [CLI_CHANNELS.ASSET_VISUALIZE]: {
- request: AssetVisualizeRequest;
- response: AssetVisualizeResult;
- };
- [CLI_CHANNELS.ASSET_ANALYZE]: {
- request: AssetAnalyzeRequest;
- response: AssetAnalyzeResult;
- };
- [CLI_CHANNELS.SELECTION_LIST]: { request: void; response: NodeRef[] };
- [CLI_CHANNELS.SELECTION_SET]: {
- request: { ids: number[] };
- response: NodeRef[];
- };
- [CLI_CHANNELS.SELECTION_FOCUS]: { request: void; response: NodeRef[] };
- [CLI_CHANNELS.NODE_LIST]: {
- request: { ids?: number[] };
- response: NodeListResult[];
- };
- [CLI_CHANNELS.NODE_TREE]: {
- request: { id?: number; depth?: number };
- response: NodeTree[];
- };
- [CLI_CHANNELS.NODE_GREP]: {
- request: NodeGrepRequest;
- response: NodeGrepResult[];
- };
- [CLI_CHANNELS.NODE_SCREENSHOT]: {
- request: { id?: number; frame?: number };
- response: { base64: string };
- };
- [CLI_CHANNELS.MOUNT]: {
- request: MountRequest;
- response: MountResult;
- };
- [CLI_CHANNELS.NODE_INSERT]: {
- request: NodeInsertRequest;
- response: MountResult;
- };
- [CLI_CHANNELS.NODE_DELETE]: {
- request: { ids: number[] };
- response: NodeDeleteResult[];
- };
- [CLI_CHANNELS.NODE_PATCH]: {
- request: { patches: NodePatch[] };
- response: NodePatchResult[];
- };
- [CLI_CHANNELS.NODE_DUPLICATE]: {
- request: { ids: number[] };
- response: NodeDuplicateResult[];
- };
- [CLI_CHANNELS.NODE_RENDER]: {
- request: NodeRenderRequest;
- response: NodeRenderResult;
- };
- [CLI_CHANNELS.PROJECT_ACTIVE]: {
- request: void;
- response: { id: string; name: string } | null;
- };
- [CLI_CHANNELS.PROJECT_LIST]: {
- request: void;
- response: ProjectSummary[];
- };
- [CLI_CHANNELS.PROJECT_CREATE]: {
- request: { name?: string };
- response: { id: string; name: string };
- };
- [CLI_CHANNELS.PROJECT_DELETE]: {
- request: { id: string };
- response: { id: string; name: string };
- };
- [CLI_CHANNELS.PROJECT_OPEN]: {
- request: { id: string };
- response: { id: string; name: string } | null;
- };
- [CLI_CHANNELS.MODELS]: {
- request: ModelsRequest;
- response: ModelInfo[];
- };
- [CLI_CHANNELS.VOICES]: {
- request: void;
- response: VoiceInfo[];
- };
- [CLI_CHANNELS.WHOAMI]: {
- request: void;
- response: { id: string; email: string; provider: string } | null;
- };
-};
-
-export type CliRequestChannel = keyof CliRequestMap;
-
-export type CliRequest = {
- id: string;
- channel: CliRequestChannel;
- data: unknown;
-};
-
-export type CliReply =
- | { id: string; ok: true; data: unknown }
- | { id: string; ok: false; error: string };
diff --git a/apps/cli/src/cli-client.ts b/apps/cli/src/cli-client.ts
index cc8f871f..fe1da25d 100644
--- a/apps/cli/src/cli-client.ts
+++ b/apps/cli/src/cli-client.ts
@@ -3,42 +3,27 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { connect } from "node:net";
-import { randomUUID } from "node:crypto";
-import { CLI_CHANNELS, SOCKET_PATH } from "./protocol";
-import type {
- CliReply,
- CliRequest,
- CliRequestChannel,
- CliRequestMap,
- ModelsRequest,
- EncoderConfigInput,
- MountRequest,
- NodeGrepRequest,
- NodeInsertRequest,
- NodePatch,
-} from "./protocol";
+import { randomBytes } from "node:crypto";
+import type { AddressInfo } from "node:net";
+import { WebSocketServer } from "ws";
+import { createTRPCClient, TRPCClientError } from "@trpc/client";
+import type { TRPCLink } from "@trpc/client";
+import { observable } from "@trpc/server/observable";
+import { SOCKET_PATH } from "./protocol";
+import type { CliHandshake, CliHandshakeReply, CliReply, CliRequest } from "./protocol";
+import type { AppRouter } from "../../web/src/context/electron/router";
const DEFAULT_TIMEOUT_MS = 60000;
-const GENERATE_TIMEOUT_MS = 600000;
+export const GENERATE_TIMEOUT_MS = 600000;
-export function cliRequest<C extends CliRequestChannel>(
- channel: C,
- data: CliRequestMap[C]["request"],
- timeoutMs: number = DEFAULT_TIMEOUT_MS,
-): Promise<CliRequestMap[C]["response"]> {
+// Asks the app (via the unix socket) to have the renderer dial our WebSocket
+// server. Main replies once the connect info has been delivered, so a
+// rejection here means the app is down or the renderer never became ready.
+function requestConnection(handshake: CliHandshake, timeoutMs: number): Promise<void> {
return new Promise((resolve, reject) => {
const sock = connect(SOCKET_PATH);
let buf = "";
let settled = false;
- const envelope: CliRequest = {
- id: randomUUID(),
- channel,
- data,
- };
-
- // Destroy the socket explicitly on completion. Without this, lingering
- // socket handles (idle timer, half-closed state) can keep the Node event
- // loop alive past `console.log(result)`, preventing the CLI from exiting.
const settle = (fn: () => void) => {
if (settled) return;
settled = true;
@@ -48,97 +33,129 @@ export function cliRequest<C extends CliRequestChannel>(
sock.setEncoding("utf8");
sock.setTimeout(timeoutMs, () =>
- settle(() => reject(new Error("Timed out waiting for response"))),
+ settle(() => reject(new Error("Timed out waiting for the app to accept the connection"))),
);
- sock.on("connect", () => sock.end(JSON.stringify(envelope)));
+ sock.on("connect", () => sock.end(JSON.stringify(handshake)));
sock.on("data", (chunk) => {
buf += chunk;
});
sock.on("end", () => {
- let reply: CliReply;
+ let reply: CliHandshakeReply;
try {
- reply = JSON.parse(buf) as CliReply;
+ reply = JSON.parse(buf) as CliHandshakeReply;
} catch (e) {
settle(() => reject(e instanceof Error ? e : new Error(String(e))));
return;
}
- if (reply.ok) {
- settle(() => resolve(reply.data as CliRequestMap[C]["response"]));
- } else {
- settle(() => reject(new Error(reply.error)));
- }
+ if (reply.ok) settle(resolve);
+ else settle(() => reject(new Error(reply.error)));
});
sock.on("error", (err) => settle(() => reject(err)));
});
}
-export const cliAPI = {
- context: () => cliRequest(CLI_CHANNELS.CONTEXT, undefined),
- addAssets: (paths: string[], folderId?: string) =>
- cliRequest(CLI_CHANNELS.ASSETS_ADD, { paths, folderId }),
- listAssets: (ids?: string[]) => cliRequest(CLI_CHANNELS.ASSETS_LIST, { ids }),
- assetTree: (folderId?: string, depth?: number) =>
- cliRequest(CLI_CHANNELS.ASSET_TREE, { folderId, depth }),
- deleteAssets: (ids: string[]) => cliRequest(CLI_CHANNELS.ASSETS_DELETE, { ids }),
- moveAssets: (ids: string[], to?: string) => cliRequest(CLI_CHANNELS.ASSETS_MOVE, { ids, to }),
- exportAssets: (ids: string[], output: string, isDir: boolean) =>
- cliRequest(CLI_CHANNELS.ASSETS_EXPORT, { ids, output, isDir }, GENERATE_TIMEOUT_MS),
- listFolders: (parentId?: string) => cliRequest(CLI_CHANNELS.FOLDERS_LIST, { parentId }),
- createFolder: (name: string, parentId?: string) =>
- cliRequest(CLI_CHANNELS.FOLDER_CREATE, { name, parentId }),
- renameFolder: (id: string, name: string) => cliRequest(CLI_CHANNELS.FOLDER_RENAME, { id, name }),
- moveFolders: (ids: string[], to?: string) => cliRequest(CLI_CHANNELS.FOLDERS_MOVE, { ids, to }),
- deleteFolders: (ids: string[]) => cliRequest(CLI_CHANNELS.FOLDERS_DELETE, { ids }),
- assetProbe: (id: string) => cliRequest(CLI_CHANNELS.ASSET_PROBE, { id }),
- assetFrame: (id: string, times?: number[], resolution?: number) =>
- cliRequest(CLI_CHANNELS.ASSET_FRAME, { id, times, resolution }),
- assetTranscribe: (id: string, start?: number, end?: number) =>
- cliRequest(CLI_CHANNELS.ASSET_TRANSCRIBE, { id, start, end }, GENERATE_TIMEOUT_MS),
- assetVisualize: (id: string, start?: number, end?: number, scale?: number) =>
- cliRequest(CLI_CHANNELS.ASSET_VISUALIZE, { id, start, end, scale }),
- assetAnalyze: (id: string, prompt?: string, start?: number, end?: number, stripVideo?: boolean) =>
- cliRequest(CLI_CHANNELS.ASSET_ANALYZE, { id, prompt, start, end, stripVideo }, GENERATE_TIMEOUT_MS),
- listSelection: () => cliRequest(CLI_CHANNELS.SELECTION_LIST, undefined),
- setSelection: (ids: number[]) => cliRequest(CLI_CHANNELS.SELECTION_SET, { ids }),
- focusSelection: () => cliRequest(CLI_CHANNELS.SELECTION_FOCUS, undefined),
- listNodes: (ids?: number[]) => cliRequest(CLI_CHANNELS.NODE_LIST, { ids }),
- nodeTree: (id?: number, depth?: number) => cliRequest(CLI_CHANNELS.NODE_TREE, { id, depth }),
- grepNodes: (req: NodeGrepRequest) => cliRequest(CLI_CHANNELS.NODE_GREP, req),
- nodeScreenshot: (id?: number, frame?: number) => cliRequest(CLI_CHANNELS.NODE_SCREENSHOT, { id, frame }),
- mount: (req: MountRequest) => cliRequest(CLI_CHANNELS.MOUNT, req, GENERATE_TIMEOUT_MS),
- insertNode: (req: NodeInsertRequest) =>
- cliRequest(CLI_CHANNELS.NODE_INSERT, req, GENERATE_TIMEOUT_MS),
- deleteNodes: (ids: number[]) => cliRequest(CLI_CHANNELS.NODE_DELETE, { ids }),
- patchNodes: (patches: NodePatch[]) => cliRequest(CLI_CHANNELS.NODE_PATCH, { patches }),
- duplicateNodes: (ids: number[]) => cliRequest(CLI_CHANNELS.NODE_DUPLICATE, { ids }),
- renderNode: (output: string, id?: number, config?: EncoderConfigInput) =>
- cliRequest(CLI_CHANNELS.NODE_RENDER, { id, output, config }, GENERATE_TIMEOUT_MS),
- activeProject: () => cliRequest(CLI_CHANNELS.PROJECT_ACTIVE, undefined),
- listProjects: () => cliRequest(CLI_CHANNELS.PROJECT_LIST, undefined),
- createProject: (name?: string) => cliRequest(CLI_CHANNELS.PROJECT_CREATE, { name }),
- deleteProject: (id: string) => cliRequest(CLI_CHANNELS.PROJECT_DELETE, { id }),
- openProject: (id: string) => cliRequest(CLI_CHANNELS.PROJECT_OPEN, { id }),
- models: (req: ModelsRequest) => cliRequest(CLI_CHANNELS.MODELS, req),
- voices: () => cliRequest(CLI_CHANNELS.VOICES, undefined),
- ping: () => cliRequest(CLI_CHANNELS.PING, undefined),
- whoami: () => cliRequest(CLI_CHANNELS.WHOAMI, undefined),
-};
+async function transport(request: CliRequest, timeoutMs: number): Promise<unknown> {
+ const token = randomBytes(16).toString("hex");
+ // Frame batches and other base64 replies can exceed ws's 100 MiB default,
+ // so disable the payload cap; the server only lives for one request.
+ const wss = new WebSocketServer({ host: "127.0.0.1", port: 0, maxPayload: 0 });
+
+ try {
+ const reply = await new Promise<CliReply>((resolve, reject) => {
+ let settled = false;
+ const timer = setTimeout(() => {
+ settle(() => reject(new Error("Timed out waiting for response")));
+ }, timeoutMs);
+ const settle = (fn: () => void) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ fn();
+ };
+
+ wss.on("error", (err) => settle(() => reject(err)));
+ wss.on("connection", (ws, req) => {
+ const url = new URL(req.url ?? "/", "ws://127.0.0.1");
+ if (url.searchParams.get("token") !== token) {
+ ws.terminate();
+ return;
+ }
+ ws.on("message", (raw) => {
+ try {
+ const parsed = JSON.parse(raw.toString()) as CliReply;
+ settle(() => resolve(parsed));
+ } catch (e) {
+ settle(() => reject(e instanceof Error ? e : new Error(String(e))));
+ }
+ });
+ ws.on("close", () =>
+ settle(() => reject(new Error("App disconnected before replying"))),
+ );
+ ws.on("error", (err) => settle(() => reject(err)));
+ ws.send(JSON.stringify(request));
+ });
+
+ wss.once("listening", () => {
+ const { port } = wss.address() as AddressInfo;
+ requestConnection({ port, token }, timeoutMs).catch((err) =>
+ settle(() => reject(err instanceof Error ? err : new Error(String(err)))),
+ );
+ });
+ });
+
+ if (reply.ok) return reply.data;
+ throw new Error(reply.error);
+ } finally {
+ // Tear down explicitly so no lingering handles keep the Node event loop
+ // alive past `console.log(result)` and block the CLI from exiting.
+ for (const client of wss.clients) client.terminate();
+ wss.close();
+ }
+}
+
+// Terminating link: each operation runs over its own short-lived WebSocket
+// server that the renderer dials in to. Long-running procedures pass
+// { context: { timeoutMs } } at the call site.
+const cliLink: TRPCLink<AppRouter> =
+ () =>
+ ({ op }) =>
+ observable((observer) => {
+ const timeoutMs =
+ typeof op.context.timeoutMs === "number" ? op.context.timeoutMs : DEFAULT_TIMEOUT_MS;
+ transport({ path: op.path, input: op.input }, timeoutMs)
+ .then((data) => {
+ observer.next({ result: { data } });
+ observer.complete();
+ })
+ .catch((err) => observer.error(TRPCClientError.from(err as Error)));
+ // No cancellation: the CLI process exits when the command settles.
+ return () => {};
+ });
+
+export const editor = createTRPCClient<AppRouter>({ links: [cliLink] });
+
+// Transport failures surface as TRPCClientError wrapping the socket error;
+// unwrap to reach errno codes like ENOENT/ECONNREFUSED.
+export function errnoCode(e: unknown): string | undefined {
+ const cause = (e as { cause?: unknown }).cause;
+ return ((cause ?? e) as NodeJS.ErrnoException).code;
+}
-// Bridges the cold-start gap after launching the app. The `cli:ping` channel
-// is handled by the renderer-side bridge and only completes once main has
-// forwarded the request to a ready renderer — so a single round-trip is
-// enough once the socket is up. The retry loop only handles the brief window
-// before the socket itself binds (ENOENT/ECONNREFUSED).
+// 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
+// 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> {
const start = Date.now();
let lastError: unknown = null;
while (Date.now() - start < timeoutMs) {
try {
- await cliAPI.ping();
+ await editor.ping.query();
return;
} catch (e) {
lastError = e;
- const code = (e as NodeJS.ErrnoException).code;
+ const code = errnoCode(e);
if (code !== "ENOENT" && code !== "ECONNREFUSED") throw e;
await new Promise((r) => setTimeout(r, 200));
}
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 516f8cd6..b1879314 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -11,12 +11,15 @@ import { extname, isAbsolute, join, resolve } from "node:path";
import { Command } from "commander";
import { version } from "../../../package.json";
import { parseTime, TIME_FPS } from "@diffusionstudio/jsx";
-import { cliAPI, waitForCliSocket } from "./cli-client";
+import { editor, errnoCode, waitForCliSocket, GENERATE_TIMEOUT_MS } from "./cli-client";
import { compileProject } from "./compile-project";
import { listLocalFonts } from "./fonts";
import { openFolder } from "./open-folder";
import { fetchVideo } from "./ytdlp";
-import type { EncoderConfigInput } from "./protocol";
+import type { EncoderConfigInput, NodePatch } from "./protocol";
+
+// Long-running commands (renders, AI generation) override the default 60s.
+const GENERATE = { context: { timeoutMs: GENERATE_TIMEOUT_MS } };
const APP_NAME = "Diffusion Studio";
const PROTOCOL = "diffusion";
@@ -98,7 +101,7 @@ async function openTarget(target: string | undefined, background: boolean): Prom
}
function handleSocketError(e: unknown): never {
- const code = (e as NodeJS.ErrnoException).code;
+ const code = errnoCode(e);
if (code === "ENOENT" || code === "ECONNREFUSED") {
console.error(`${APP_NAME} is not running. Launch the app first, then retry.`);
} else {
@@ -141,7 +144,7 @@ async function addAssets(paths: string[], opts: AssetAddOptions): Promise<void>
}
try {
- const results = await cliAPI.addAssets(absolutePaths, opts.folder);
+ const results = await editor.asset.add.mutate({ paths: absolutePaths, folderId: opts.folder });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -151,7 +154,7 @@ async function addAssets(paths: string[], opts: AssetAddOptions): Promise<void>
async function listAssets(ids: string[]): Promise<void> {
try {
// No ids → every asset in the library; with ids → those specific assets.
- const results = await cliAPI.listAssets(ids.length ? ids : undefined);
+ const results = await editor.asset.list.query({ ids: ids.length ? ids : undefined });
let failed = false;
for (const result of results) {
if (result.status === "fulfilled") {
@@ -181,7 +184,7 @@ async function assetTree(opts: AssetTreeOptions): Promise<void> {
}
try {
- const results = await cliAPI.assetTree(opts.folder, depth);
+ const results = await editor.asset.tree.query({ folderId: opts.folder, depth });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -194,7 +197,7 @@ async function deleteAssets(ids: string[]): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.deleteAssets(ids);
+ const results = await editor.asset.delete.mutate({ ids });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -209,7 +212,7 @@ async function moveAssets(ids: string[], opts: MoveOptions): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.moveAssets(ids, opts.to);
+ const results = await editor.asset.move.mutate({ ids, to: opts.to });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -249,7 +252,7 @@ async function exportAssets(ids: string[], opts: AssetExportOptions): Promise<vo
const stop = startSpinner(ids.length > 1 ? "Exporting assets" : "Exporting asset");
try {
- const results = await cliAPI.exportAssets(ids, output, isDir);
+ const results = await editor.asset.export.mutate({ ids, output, isDir }, GENERATE);
stop();
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
@@ -260,7 +263,7 @@ async function exportAssets(ids: string[], opts: AssetExportOptions): Promise<vo
async function listFolders(parentId: string | undefined): Promise<void> {
try {
- const results = await cliAPI.listFolders(parentId);
+ const results = await editor.folder.list.query({ parentId });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -271,7 +274,7 @@ type FolderCreateOptions = { parent?: string };
async function createFolder(name: string, opts: FolderCreateOptions): Promise<void> {
try {
- const result = await cliAPI.createFolder(name, opts.parent);
+ const result = await editor.folder.create.mutate({ name, parentId: opts.parent });
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -280,7 +283,7 @@ async function createFolder(name: string, opts: FolderCreateOptions): Promise<vo
async function renameFolder(id: string, name: string): Promise<void> {
try {
- const result = await cliAPI.renameFolder(id, name);
+ const result = await editor.folder.rename.mutate({ id, name });
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -293,7 +296,7 @@ async function moveFolders(ids: string[], opts: MoveOptions): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.moveFolders(ids, opts.to);
+ const results = await editor.folder.move.mutate({ ids, to: opts.to });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -306,7 +309,7 @@ async function deleteFolders(ids: string[]): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.deleteFolders(ids);
+ const results = await editor.folder.delete.mutate({ ids });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -315,7 +318,7 @@ async function deleteFolders(ids: string[]): Promise<void> {
async function listSelection(): Promise<void> {
try {
- const results = await cliAPI.listSelection();
+ const results = await editor.selection.list.query();
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -324,7 +327,7 @@ async function listSelection(): Promise<void> {
async function setSelection(ids: string[]): Promise<void> {
try {
- const results = await cliAPI.setSelection(parseNodeIds(ids));
+ const results = await editor.selection.set.mutate({ ids: parseNodeIds(ids) });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -333,7 +336,7 @@ async function setSelection(ids: string[]): Promise<void> {
async function focusSelection(): Promise<void> {
try {
- const results = await cliAPI.focusSelection();
+ const results = await editor.selection.focus.mutate();
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -343,7 +346,7 @@ async function focusSelection(): Promise<void> {
async function listNodes(ids: string[]): Promise<void> {
try {
// No ids → root scenes; with ids → those specific nodes.
- const results = await cliAPI.listNodes(ids.length ? parseNodeIds(ids) : undefined);
+ const results = await editor.node.list.query({ ids: ids.length ? parseNodeIds(ids) : undefined });
let failed = false;
for (const result of results) {
if (result.status === "fulfilled") {
@@ -375,7 +378,7 @@ async function nodeTree(id: string | undefined, opts: TreeOptions): Promise<void
}
try {
- const results = await cliAPI.nodeTree(eid, depth);
+ const results = await editor.node.tree.query({ id: eid, depth });
for (const result of results) {
console.log(JSON.stringify(result));
}
@@ -403,7 +406,7 @@ async function grepNodes(pattern: string, id: string | undefined, opts: NodeGrep
const eid = id !== undefined ? parseNodeIds([id])[0] : undefined;
try {
- const results = await cliAPI.grepNodes({
+ const results = await editor.node.grep.query({
pattern,
ignoreCase: opts.ignoreCase,
id: eid,
@@ -438,7 +441,7 @@ async function nodeScreenshot(id: string | undefined, opts: ScreenshotOptions):
}
try {
- const { base64 } = await cliAPI.nodeScreenshot(eid, frame);
+ const { base64 } = await editor.node.screenshot.query({ id: eid, frame });
const path = join(tmpdir(), `${randomUUID()}.png`);
writeFileSync(path, Buffer.from(base64, "base64"));
console.log(JSON.stringify({ path }));
@@ -467,7 +470,7 @@ async function assetFrame(ref: string, opts: AssetFrameOptions): Promise<void> {
const assetId = await resolveAssetRef(ref);
const dir = opts.output ?? tmpdir();
try {
- const frames = await cliAPI.assetFrame(assetId, times, resolution);
+ const frames = await editor.asset.frame.query({ id: assetId, times, resolution });
for (const { time, base64 } of frames) {
const path = join(dir, `${randomUUID()}.png`);
writeFileSync(path, Buffer.from(base64, "base64"));
@@ -493,7 +496,12 @@ async function resolveAssetRef(ref: string): Promise<string> {
const stop = startSpinner("Adding asset");
try {
- const [result] = await cliAPI.addAssets([absPath]);
+ // The handler types per-item results as a loose union; narrow by hand.
+ const [result] = (await editor.asset.add.mutate({ paths: [absPath] })) as Array<{
+ status: string;
+ id?: unknown;
+ error?: string;
+ }>;
stop();
if (!result || result.status !== "fulfilled" || typeof result.id !== "string") {
console.error(result?.error ?? `Failed to add asset: ${absPath}`);
@@ -510,7 +518,7 @@ async function assetProbe(ref: string): Promise<void> {
const assetId = await resolveAssetRef(ref);
const stop = startSpinner("Probing asset");
try {
- const result = await cliAPI.assetProbe(assetId);
+ const result = await editor.asset.probe.query({ id: assetId });
stop();
console.log(JSON.stringify(result));
} catch (e) {
@@ -532,7 +540,7 @@ async function assetTranscribe(ref: string, opts: AssetTranscribeOptions): Promi
const assetId = await resolveAssetRef(ref);
const stop = startSpinner("Transcribing asset");
try {
- const result = await cliAPI.assetTranscribe(assetId, start, end);
+ const result = await editor.asset.transcribe.query({ id: assetId, start, end }, GENERATE);
stop();
console.log(JSON.stringify(result));
} catch (e) {
@@ -554,7 +562,10 @@ async function assetAnalyze(ref: string, opts: AssetAnalyzeOptions): Promise<voi
const assetId = await resolveAssetRef(ref);
const stop = startSpinner("Analyzing asset");
try {
- const result = await cliAPI.assetAnalyze(assetId, opts.prompt, start, end, opts.stripVideo);
+ const result = await editor.asset.analyze.query(
+ { id: assetId, prompt: opts.prompt, start, end, stripVideo: opts.stripVideo },
+ GENERATE,
+ );
stop();
console.log(JSON.stringify(result));
} catch (e) {
@@ -597,7 +608,7 @@ async function assetVisualize(ref: string, opts: AssetVisualizeOptions): Promise
const path = opts.output ?? join(tmpdir(), `${randomUUID()}.png`);
const stop = startSpinner("Rendering visualization");
try {
- const { base64, ...rest } = await cliAPI.assetVisualize(assetId, start, end, scale);
+ const { base64, ...rest } = await editor.asset.visualize.query({ id: assetId, start, end, scale });
stop();
writeFileSync(path, Buffer.from(base64, "base64"));
console.log(JSON.stringify({ path, ...rest }));
@@ -648,7 +659,7 @@ async function mountProject(path: string | undefined, opts: MountOptions): Promi
const stop = startSpinner("Mounting project");
try {
- const result = await cliAPI.mount({ code });
+ const result = await editor.mount.mutate({ code }, GENERATE);
stop();
if (result.status === "rejected") {
console.error(result.error);
@@ -679,7 +690,7 @@ async function nodeInsert(parentId: string, path: string | undefined, opts: Node
const stop = startSpinner("Inserting entities");
try {
- const result = await cliAPI.insertNode({ code, parentId: eid, index });
+ const result = await editor.node.insert.mutate({ code, parentId: eid, index }, GENERATE);
stop();
if (result.status === "rejected") {
console.error(result.error);
@@ -697,7 +708,7 @@ async function deleteNodes(ids: string[]): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.deleteNodes(parseNodeIds(ids));
+ const results = await editor.node.delete.mutate({ ids: parseNodeIds(ids) });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -762,7 +773,7 @@ async function patchNodes(path: string | undefined, opts: JsonPayloadOptions): P
process.exit(1);
}
try {
- const results = await cliAPI.patchNodes(payload as Parameters<typeof cliAPI.patchNodes>[0]);
+ const results = await editor.node.patch.mutate({ patches: payload as NodePatch[] });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -775,7 +786,7 @@ async function duplicateNodes(ids: string[]): Promise<void> {
process.exit(1);
}
try {
- const results = await cliAPI.duplicateNodes(parseNodeIds(ids));
+ const results = await editor.node.duplicate.mutate({ ids: parseNodeIds(ids) });
for (const result of results) console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -811,7 +822,7 @@ async function nodeRender(
const stop = startSpinner("Rendering scene");
try {
- const { path } = await cliAPI.renderNode(output, eid, config);
+ const { path } = await editor.node.render.mutate({ id: eid, output, config }, GENERATE);
stop();
console.log(JSON.stringify({ path }));
} catch (e) {
@@ -822,7 +833,7 @@ async function nodeRender(
async function activeProject(): Promise<void> {
try {
- const result = await cliAPI.activeProject();
+ const result = await editor.project.active.query();
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -831,7 +842,7 @@ async function activeProject(): Promise<void> {
async function listProjects(): Promise<void> {
try {
- const result = await cliAPI.listProjects();
+ const result = await editor.project.list.query();
for (const project of result) console.log(JSON.stringify(project));
} catch (e) {
handleSocketError(e);
@@ -840,7 +851,7 @@ async function listProjects(): Promise<void> {
async function createProject(name?: string): Promise<void> {
try {
- const result = await cliAPI.createProject(name);
+ const result = await editor.project.create.mutate({ name });
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -849,7 +860,7 @@ async function createProject(name?: string): Promise<void> {
async function openProject(id: string): Promise<void> {
try {
- const result = await cliAPI.openProject(id);
+ const result = await editor.project.open.mutate({ id });
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -858,7 +869,7 @@ async function openProject(id: string): Promise<void> {
async function deleteProject(id: string): Promise<void> {
try {
- const result = await cliAPI.deleteProject(id);
+ const result = await editor.project.delete.mutate({ id });
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -867,7 +878,7 @@ async function deleteProject(id: string): Promise<void> {
async function context(): Promise<void> {
try {
- const result = await cliAPI.context();
+ const result = await editor.context.query();
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -876,7 +887,7 @@ async function context(): Promise<void> {
async function whoami(): Promise<void> {
try {
- const result = await cliAPI.whoami();
+ const result = await editor.whoami.query();
console.log(JSON.stringify(result));
} catch (e) {
handleSocketError(e);
@@ -910,7 +921,7 @@ async function listModels(type: string | undefined): Promise<void> {
process.exit(1);
}
try {
- const models = await cliAPI.models({ type: type as "image" | "video" | "audio" | undefined });
+ const models = await editor.models.query({ type: type as "image" | "video" | "audio" | undefined });
for (const model of models) console.log(JSON.stringify(model));
} catch (e) {
handleSocketError(e);
@@ -919,7 +930,7 @@ async function listModels(type: string | undefined): Promise<void> {
async function listVoices(): Promise<void> {
try {
- const voices = await cliAPI.voices();
+ const voices = await editor.voices.query();
for (const voice of voices) console.log(JSON.stringify(voice));
} catch (e) {
handleSocketError(e);
diff --git a/apps/cli/src/open-folder.ts b/apps/cli/src/open-folder.ts
index 7ecbbc4c..4aef5306 100644
--- a/apps/cli/src/open-folder.ts
+++ b/apps/cli/src/open-folder.ts
@@ -5,7 +5,7 @@
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { readdir } from "node:fs/promises";
import { basename, extname, join } from "node:path";
-import { cliAPI } from "./cli-client";
+import { editor } from "./cli-client";
const MARKER_FILENAME = ".dapi";
const MARKER_VERSION = 1;
@@ -105,7 +105,7 @@ async function ensureFolder(segments: string[], cache: Map<string, string>) {
const cached = cache.get(key);
if (cached !== undefined) return cached;
const parentId = await ensureFolder(segments.slice(0, -1), cache);
- const folder = await cliAPI.createFolder(segments[segments.length - 1], parentId);
+ const folder = await editor.folder.create.mutate({ name: segments[segments.length - 1]!, parentId });
cache.set(key, folder.id);
return folder.id;
}
@@ -113,7 +113,7 @@ async function ensureFolder(segments: string[], cache: Map<string, string>) {
async function waitForActiveProject(expectedId: string, timeoutMs = 10000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
- const active = await cliAPI.activeProject().catch(() => null);
+ const active = await editor.project.active.query().catch(() => null);
if (active?.id === expectedId) return;
await new Promise((r) => setTimeout(r, 50));
}
@@ -131,7 +131,7 @@ export async function openFolder(folderPath: string): Promise<OpenFolderResult>
const marker = readMarker(folderPath);
if (marker) {
- const opened = await cliAPI.openProject(marker.projectId);
+ const opened = await editor.project.open.mutate({ id: marker.projectId });
if (opened) {
await waitForActiveProject(opened.id);
return { project: opened, created: false, imported: 0 };
@@ -140,14 +140,14 @@ export async function openFolder(folderPath: string): Promise<OpenFolderResult>
}
const assetDirs = await collectSupportedAssets(folderPath);
- const project = await cliAPI.createProject(basename(folderPath));
+ const project = await editor.project.create.mutate({ name: basename(folderPath) });
await waitForActiveProject(project.id);
let imported = 0;
const folderIds = new Map<string, string>();
for (const { segments, paths } of assetDirs) {
const folderId = await ensureFolder(segments, folderIds);
- const results = await cliAPI.addAssets(paths, folderId);
+ const results = await editor.asset.add.mutate({ paths, folderId });
if (Array.isArray(results)) {
imported += results.filter(
(r: { status?: string }) => r?.status === "fulfilled",
diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json
index af9f7d7d..0dd3fce3 100644
--- a/apps/cli/tsconfig.json
+++ b/apps/cli/tsconfig.json
@@ -2,15 +2,39 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.tsbuildinfo",
+ // The AppRouter type import in cli-client.ts pulls renderer sources into
+ // this program, so the web app's compiler settings (DOM, solid JSX, vite
+ // types, aliases) apply here on top of the node ones.
+ "useDefineForClassFields": true,
+ "erasableSyntaxOnly": false,
"lib": [
- "es2024"
+ "es2024",
+ "DOM",
+ "DOM.Iterable"
],
"types": [
- "node"
+ "node",
+ "vite-plugin-solid-svg/types-component-solid",
+ "vite/client",
+ "@types/audioworklet",
+ "@types/wicg-file-system-access"
],
- "resolveJsonModule": true
+ "resolveJsonModule": true,
+ "allowImportingTsExtensions": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "baseUrl": "./",
+ "paths": {
+ "@/*": [
+ "../web/src/*"
+ ],
+ "@desktop/*": [
+ "../desktop/src/*"
+ ]
+ }
},
"include": [
- "src"
+ "src",
+ "../web/src/vite-env.d.ts"
]
}
diff --git a/apps/desktop/scripts/stage-cli.mjs b/apps/desktop/scripts/stage-cli.mjs
index 2183f24f..90590cda 100644
--- a/apps/desktop/scripts/stage-cli.mjs
+++ b/apps/desktop/scripts/stage-cli.mjs
@@ -17,7 +17,10 @@ const desktopDir = join(dirname(fileURLToPath(import.meta.url)), "..");
const cliDir = join(desktopDir, "..", "cli");
const stageDir = join(desktopDir, "cli");
-// Must match the --external list in the apps/cli build script.
+// Must match the --external list in the apps/cli build script, minus ws's
+// optional native addons (bufferutil, utf-8-validate): those are external
+// only so the bundle doesn't choke on them, and ws falls back to its JS
+// implementations when they are absent.
const EXTERNALS = ["esbuild", "@babel/core", "@babel/preset-typescript", "babel-preset-solid"];
const cliPkg = JSON.parse(readFileSync(join(cliDir, "package.json"), "utf8"));
diff --git a/apps/desktop/src/cli-server.ts b/apps/desktop/src/cli-server.ts
index f7834283..c78cf301 100644
--- a/apps/desktop/src/cli-server.ts
+++ b/apps/desktop/src/cli-server.ts
@@ -5,15 +5,16 @@
import { existsSync, unlinkSync } from "node:fs";
import { createServer } from "node:net";
import type { Server, Socket } from "node:net";
-import { app, BrowserWindow, ipcMain } from "electron";
+import { app, BrowserWindow } from "electron";
import { CLI_WIRE, SOCKET_PATH } from "@diffusionstudio/cli/protocol";
-import type { CliReply, CliRequest } from "@diffusionstudio/cli/protocol";
+import type { CliHandshake, CliHandshakeReply } from "@diffusionstudio/cli/protocol";
import { mainBridge } from "./main-manager";
import { MAIN_CHANNELS } from "./main-channels";
let cliServer: Server | null = null;
let currentWindow: BrowserWindow | null = null;
let headless = false;
+let windowLifecycleBound = false;
export function isHeadless(): boolean {
return headless;
@@ -27,17 +28,6 @@ function enableHeadless(): void {
}
}
-const pending = new Map<string, Socket>();
-let forwardListenerBound = false;
-let windowLifecycleBound = false;
-
-function resetRenderer(reason: string): void {
- for (const [id, sock] of pending) {
- finish(id, { id, ok: false, error: reason }, sock);
- }
- pending.clear();
-}
-
// Resolves once the current window has finished loading.
function waitForRendererReady(timeoutMs = 30000): Promise<void> {
if (!currentWindow || currentWindow.isDestroyed()) {
@@ -78,69 +68,40 @@ function waitForRendererReady(timeoutMs = 30000): Promise<void> {
});
}
-function attachWindowLifecycle(window: BrowserWindow): void {
- currentWindow = window;
-
- window.webContents.on("did-start-loading", () => resetRenderer("Renderer reloading"));
- window.webContents.on("render-process-gone", () => resetRenderer("Renderer crashed"));
- window.on("closed", () => {
- if (currentWindow === window) {
- currentWindow = null;
- }
- resetRenderer("Window closed");
- });
-}
-
function bindWindowLifecycle(): void {
if (windowLifecycleBound) return;
windowLifecycleBound = true;
- app.on("browser-window-created", (_event, window) => attachWindowLifecycle(window));
- // Catch any window that was created before the server started.
- for (const window of BrowserWindow.getAllWindows()) {
- attachWindowLifecycle(window);
- }
-}
-
-function finish(id: string, reply: CliReply, sock?: Socket): void {
- const target = sock ?? pending.get(id);
- if (!target) return;
- pending.delete(id);
- if (!target.destroyed) target.end(JSON.stringify(reply));
-}
-
-function bindForwardListener(): void {
- if (forwardListenerBound) return;
- forwardListenerBound = true;
- ipcMain.on(CLI_WIRE.FORWARD_REPLY, (_event, reply: CliReply) => {
- finish(reply.id, reply);
+ app.on("browser-window-created", (_event, window) => {
+ currentWindow = window;
+ window.on("closed", () => {
+ if (currentWindow === window) currentWindow = null;
+ });
});
+ // Catch any window that was created before the server started.
+ const windows = BrowserWindow.getAllWindows();
+ if (windows.length > 0) currentWindow = windows[windows.length - 1]!;
}
-async function forwardToRenderer(req: CliRequest, sock: Socket): Promise<void> {
- pending.set(req.id, sock);
- sock.once("close", () => {
- // CLI hung up before we could reply — drop the entry so a late reply is
- // discarded rather than written to a destroyed socket.
- if (pending.get(req.id) === sock) {
- pending.delete(req.id);
- }
- });
-
+// Relays the CLI's connect info to the renderer, which dials the CLI's
+// WebSocket server directly. The reply confirms delivery only; from there
+// the request/response traffic bypasses main entirely.
+async function deliverHandshake(handshake: CliHandshake, sock: Socket): Promise<void> {
+ let reply: CliHandshakeReply;
try {
await waitForRendererReady();
if (!currentWindow || currentWindow.isDestroyed()) {
throw new Error("No window");
}
-
- currentWindow.webContents.send(CLI_WIRE.FORWARD_REQ, req);
+ currentWindow.webContents.send(CLI_WIRE.CONNECT, handshake);
+ reply = { ok: true };
} catch (err) {
- finish(req.id, { id: req.id, ok: false, error: (err as Error).message });
+ reply = { ok: false, error: (err as Error).message };
}
+ if (!sock.destroyed) sock.end(JSON.stringify(reply));
}
export function startCliServer() {
cleanupStaleSocket();
- bindForwardListener();
bindWindowLifecycle();
cliServer = createServer({ allowHalfOpen: true }, (sock: Socket) => {
@@ -153,14 +114,17 @@ export function startCliServer() {
});
sock.on("end", async () => {
sock.setTimeout(0);
- let req: CliRequest;
+ let handshake: CliHandshake;
try {
- req = JSON.parse(buf) as CliRequest;
+ handshake = JSON.parse(buf) as CliHandshake;
+ if (typeof handshake.port !== "number" || typeof handshake.token !== "string") {
+ throw new Error("Malformed handshake");
+ }
} catch {
- sock.end(JSON.stringify({ id: "unknown", ok: false, error: "Invalid JSON request" }));
+ sock.end(JSON.stringify({ ok: false, error: "Invalid handshake" }));
return;
}
- await forwardToRenderer(req, sock);
+ await deliverHandshake(handshake, sock);
});
sock.on("error", () => {
// Client hung up; nothing to do.
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 4b1d4bdd..dd975e05 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -7,15 +7,12 @@ import type { IpcRendererEvent } from "electron";
import { MAIN_WIRE } from "./main-channels";
import { CLI_WIRE } from "@diffusionstudio/cli/channels";
-const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([
- MAIN_WIRE.REQUEST,
- CLI_WIRE.FORWARD_REPLY,
-]);
+const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([MAIN_WIRE.REQUEST]);
const ALLOWED_MAIN_TO_RENDERER: ReadonlySet<string> = new Set([
MAIN_WIRE.RESPONSE,
MAIN_WIRE.EVENT,
- CLI_WIRE.FORWARD_REQ,
+ CLI_WIRE.CONNECT,
]);
contextBridge.exposeInMainWorld("desktop", {
diff --git a/apps/web/package.json b/apps/web/package.json
index e6107c6e..03828d3b 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -25,6 +25,7 @@
"@supabase/supabase-js": "^2.99.2",
"@tailwindcss/vite": "^4.1.18",
"@trpc/client": "^11.10.0",
+ "@trpc/server": "^11.10.0",
"animejs": "^4.4.1",
"bitecs": "^0.4.0",
"cmdk-solid": "^1.1.2",
diff --git a/apps/web/src/context/auth.tsx b/apps/web/src/context/auth.tsx
index 6ed145f2..be1112e7 100644
--- a/apps/web/src/context/auth.tsx
+++ b/apps/web/src/context/auth.tsx
@@ -16,12 +16,11 @@ import {
import { toast } from 'somoto';
import type { Session, User } from '@supabase/supabase-js';
import { FREE_CREDITS_QUOTA, type UserData } from '@diffusionstudio/api-contract';
-import { CLI_CHANNELS } from '@diffusionstudio/cli/channels';
import { supabase } from '@/lib/supabase';
import { trpc } from '@/lib/trpc';
import { identify, resetIdentity, track } from '@/lib/analytics';
-import { cliBridge, mainBridge } from '@/lib/ipc';
+import { mainBridge } from '@/lib/ipc';
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { assert } from '@/utils';
@@ -134,22 +133,6 @@ export function AuthProvider(props: { children: JSX.Element }) {
},
);
- onMount(() => {
- if (!window.desktop) return;
- // Can't be moved to engine provider otherwise the handler
- // would not be present if the user is signed out.
- const unsubscribe = cliBridge.handle(CLI_CHANNELS.WHOAMI, () => {
- const user = session()?.user;
- if (!user) return null;
- return {
- id: user.id,
- email: user.email ?? "",
- provider: user.app_metadata?.provider ?? "unknown",
- };
- });
- onCleanup(unsubscribe);
- });
-
onMount(() => {
if (!window.desktop) return;
// Must live in AuthProvider — ElectronProvider only mounts after sign-in,
diff --git a/apps/web/src/context/electron/electron.tsx b/apps/web/src/context/electron/electron.tsx
index d4ab79fc..8e365536 100644
--- a/apps/web/src/context/electron/electron.tsx
+++ b/apps/web/src/context/electron/electron.tsx
@@ -8,18 +8,10 @@ import { useEngine } from '@/context/engine';
import { useAuth } from '@/context/auth';
import { cliBridge, mainBridge } from '@/lib/ipc';
-import { CLI_CHANNELS } from '@diffusionstudio/cli/channels';
+import { createRouterCaller } from '@/lib/cli-rpc';
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { assert } from "@/utils/common";
-import { handleContextGet } from "./context";
-import { handleAssetsAdd, handleAssetsList, handleAssetTree, handleAssetsDelete, handleAssetsMove, handleAssetsExport, handleAssetProbe, handleAssetFrame, handleAssetTranscribe, handleAssetVisualize, handleAssetAnalyze } from "./assets";
-import { handleFoldersList, handleFolderCreate, handleFolderRename, handleFoldersMove, handleFoldersDelete } from "./folders";
-import { handleSelectionFocus, handleSelectionList, handleSelectionSet } from "./selection";
-import { handleNodeList, handleNodeTree, handleNodeGrep, handleNodeScreenshot, handleNodeDelete, handleNodePatch, handleNodeDuplicate, handleNodeRender } from "./node";
-import { handleMount, handleNodeInsert } from "./mount";
-import { handleProjectActive, handleProjectList, handleProjectCreate, handleProjectDelete, handleProjectOpen } from "./project";
-import { handleModels } from "./models";
-import { handleVoices } from "./voices";
+import { createAppRouter } from "./router";
import { handleGetFullscreenState, handleWindowFullscreenChange } from "./window";
import type { JSX, Accessor } from 'solid-js';
@@ -42,95 +34,28 @@ export function ElectronProvider(props: ElectronProviderProps) {
const [, setParams] = useSearchParams();
const [isFullscreen, { mutate }] = createResource(handleGetFullscreenState, { initialValue: false });
- const requireAuth = <Args extends unknown[], R>(fn: (...args: Args) => Promise<R>) => {
- return (...args: Args) => {
- assert(auth.isAuthenticated(), "Sign in required: AI generation needs a Diffusion Studio account.");
-
- return fn(...args);
- };
- };
-
createEffect(() => {
if (!window.desktop) return;
- const engineRef = () => engine;
- const unsubContext = cliBridge.handle(CLI_CHANNELS.CONTEXT, handleContextGet(engineRef));
- const unsubAssetsAdd = cliBridge.handle(CLI_CHANNELS.ASSETS_ADD, handleAssetsAdd(engineRef));
- const unsubAssetsList = cliBridge.handle(CLI_CHANNELS.ASSETS_LIST, handleAssetsList(engineRef));
- const unsubAssetTree = cliBridge.handle(CLI_CHANNELS.ASSET_TREE, handleAssetTree(engineRef));
- const unsubAssetsDelete = cliBridge.handle(CLI_CHANNELS.ASSETS_DELETE, handleAssetsDelete(engineRef));
- const unsubAssetsMove = cliBridge.handle(CLI_CHANNELS.ASSETS_MOVE, handleAssetsMove(engineRef));
- const unsubAssetsExport = cliBridge.handle(CLI_CHANNELS.ASSETS_EXPORT, handleAssetsExport(engineRef));
- const unsubFoldersList = cliBridge.handle(CLI_CHANNELS.FOLDERS_LIST, handleFoldersList(engineRef));
- const unsubFolderCreate = cliBridge.handle(CLI_CHANNELS.FOLDER_CREATE, handleFolderCreate(engineRef));
- const unsubFolderRename = cliBridge.handle(CLI_CHANNELS.FOLDER_RENAME, handleFolderRename(engineRef));
- const unsubFoldersMove = cliBridge.handle(CLI_CHANNELS.FOLDERS_MOVE, handleFoldersMove(engineRef));
- const unsubFoldersDelete = cliBridge.handle(CLI_CHANNELS.FOLDERS_DELETE, handleFoldersDelete(engineRef));
- const unsubAssetProbe = cliBridge.handle(CLI_CHANNELS.ASSET_PROBE, handleAssetProbe(engineRef));
- const unsubAssetFrame = cliBridge.handle(CLI_CHANNELS.ASSET_FRAME, handleAssetFrame(engineRef));
- const unsubAssetTranscribe = cliBridge.handle(CLI_CHANNELS.ASSET_TRANSCRIBE, handleAssetTranscribe(engineRef));
- const unsubAssetVisualize = cliBridge.handle(CLI_CHANNELS.ASSET_VISUALIZE, handleAssetVisualize(engineRef));
- const unsubAssetAnalyze = cliBridge.handle(CLI_CHANNELS.ASSET_ANALYZE, requireAuth(handleAssetAnalyze(engineRef)));
- const unsubSelectionList = cliBridge.handle(CLI_CHANNELS.SELECTION_LIST, handleSelectionList(engineRef));
- const unsubSelectionSet = cliBridge.handle(CLI_CHANNELS.SELECTION_SET, handleSelectionSet(engineRef));
- const unsubSelectionFocus = cliBridge.handle(CLI_CHANNELS.SELECTION_FOCUS, handleSelectionFocus(engineRef));
- const unsubNodeList = cliBridge.handle(CLI_CHANNELS.NODE_LIST, handleNodeList(engineRef));
- const unsubNodeTree = cliBridge.handle(CLI_CHANNELS.NODE_TREE, handleNodeTree(engineRef));
- const unsubNodeGrep = cliBridge.handle(CLI_CHANNELS.NODE_GREP, handleNodeGrep(engineRef));
- const unsubNodeScreenshot = cliBridge.handle(CLI_CHANNELS.NODE_SCREENSHOT, handleNodeScreenshot(engineRef));
- const unsubMount = cliBridge.handle(CLI_CHANNELS.MOUNT, handleMount(engineRef));
- const unsubNodeInsert = cliBridge.handle(CLI_CHANNELS.NODE_INSERT, handleNodeInsert(engineRef));
- const unsubNodeDelete = cliBridge.handle(CLI_CHANNELS.NODE_DELETE, handleNodeDelete(engineRef));
- const unsubNodePatch = cliBridge.handle(CLI_CHANNELS.NODE_PATCH, handleNodePatch(engineRef));
- const unsubNodeDuplicate = cliBridge.handle(CLI_CHANNELS.NODE_DUPLICATE, handleNodeDuplicate(engineRef));
- const unsubNodeRender = cliBridge.handle(CLI_CHANNELS.NODE_RENDER, handleNodeRender(engineRef));
- const unsubProjectActive = cliBridge.handle(CLI_CHANNELS.PROJECT_ACTIVE, handleProjectActive(engineRef));
- const unsubProjectList = cliBridge.handle(CLI_CHANNELS.PROJECT_LIST, handleProjectList());
- const unsubProjectCreate = cliBridge.handle(CLI_CHANNELS.PROJECT_CREATE, handleProjectCreate(engineRef, setParams));
- const unsubProjectDelete = cliBridge.handle(CLI_CHANNELS.PROJECT_DELETE, handleProjectDelete(engineRef, setParams));
- const unsubProjectOpen = cliBridge.handle(CLI_CHANNELS.PROJECT_OPEN, handleProjectOpen(engineRef, setParams));
- const unsubModels = cliBridge.handle(CLI_CHANNELS.MODELS, handleModels());
- const unsubVoices = cliBridge.handle(CLI_CHANNELS.VOICES, handleVoices());
+ const router = createAppRouter({
+ engine: () => engine,
+ setParams,
+ isAuthenticated: () => auth.isAuthenticated(),
+ getUser: () => {
+ const user = auth.user();
+ if (!user) return null;
+ return {
+ id: user.id,
+ email: user.email ?? "",
+ provider: user.app_metadata?.provider ?? "unknown",
+ };
+ },
+ });
+ const unsubRouter = cliBridge.register(createRouterCaller(router));
const unsubScreenChange = mainBridge.handle(MAIN_CHANNELS.WINDOW_FULLSCREEN_CHANGE, handleWindowFullscreenChange(mutate));
onCleanup(() => {
- unsubContext();
- unsubAssetsAdd();
- unsubAssetsList();
- unsubAssetTree();
- unsubAssetsDelete();
- unsubAssetsMove();
- unsubAssetsExport();
- unsubFoldersList();
- unsubFolderCreate();
- unsubFolderRename();
- unsubFoldersMove();
- unsubFoldersDelete();
- unsubAssetProbe();
- unsubAssetFrame();
- unsubAssetTranscribe();
- unsubAssetVisualize();
- unsubAssetAnalyze();
- unsubSelectionList();
- unsubSelectionSet();
- unsubSelectionFocus();
- unsubNodeList();
- unsubNodeTree();
- unsubNodeGrep();
- unsubNodeScreenshot();
- unsubMount();
- unsubNodeInsert();
- unsubNodeDelete();
- unsubNodePatch();
- unsubNodeDuplicate();
- unsubNodeRender();
- unsubProjectActive();
- unsubProjectList();
- unsubProjectCreate();
- unsubProjectDelete();
- unsubProjectOpen();
- unsubModels();
- unsubVoices();
+ unsubRouter();
unsubScreenChange();
});
});
diff --git a/apps/web/src/context/electron/router.ts b/apps/web/src/context/electron/router.ts
new file mode 100644
index 00000000..77ae2964
--- /dev/null
+++ b/apps/web/src/context/electron/router.ts
@@ -0,0 +1,91 @@
+/* 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 { t, q, m, q0, m0 } from "@/lib/cli-rpc";
+import { assert } from "@/utils/common";
+import { handleContextGet } from "./context";
+import { handleAssetsAdd, handleAssetsList, handleAssetTree, handleAssetsDelete, handleAssetsMove, handleAssetsExport, handleAssetProbe, handleAssetFrame, handleAssetTranscribe, handleAssetVisualize, handleAssetAnalyze } from "./assets";
+import { handleFoldersList, handleFolderCreate, handleFolderRename, handleFoldersMove, handleFoldersDelete } from "./folders";
+import { handleSelectionFocus, handleSelectionList, handleSelectionSet } from "./selection";
+import { handleNodeList, handleNodeTree, handleNodeGrep, handleNodeScreenshot, handleNodeDelete, handleNodePatch, handleNodeDuplicate, handleNodeRender } from "./node";
+import { handleMount, handleNodeInsert } from "./mount";
+import { handleProjectActive, handleProjectList, handleProjectCreate, handleProjectDelete, handleProjectOpen } from "./project";
+import { handleModels } from "./models";
+import { handleVoices } from "./voices";
+
+import type { Accessor } from "solid-js";
+import type { Engine } from "@/components/engine";
+import type { useSearchParams } from "@solidjs/router";
+
+type AppRouterDeps = {
+ engine: Accessor<Engine>;
+ setParams: ReturnType<typeof useSearchParams>[1];
+ isAuthenticated: () => boolean;
+ getUser: () => { id: string; email: string; provider: string } | null;
+};
+
+// The complete CLI surface. Registered by ElectronProvider, which mounts
+// whenever a project is open (sign-in not required); requests arriving
+// earlier are held by the CLI bridge until then. `ping` answers
+// `waitForCliSocket` probes.
+export function createAppRouter({ engine, setParams, isAuthenticated, getUser }: AppRouterDeps) {
+ const requireAuth = <I, O>(fn: (data: I) => Promise<O>) => (data: I) => {
+ assert(isAuthenticated(), "Sign in required: AI generation needs a Diffusion Studio account.");
+ return fn(data);
+ };
+
+ return t.router({
+ ping: t.procedure.query(() => {}),
+ whoami: t.procedure.query(() => getUser()),
+ context: q0(handleContextGet(engine)),
+ mount: m(handleMount(engine)),
+ models: q(handleModels()),
+ voices: q0(handleVoices()),
+ asset: t.router({
+ add: m(handleAssetsAdd(engine)),
+ list: q(handleAssetsList(engine)),
+ tree: q(handleAssetTree(engine)),
+ delete: m(handleAssetsDelete(engine)),
+ move: m(handleAssetsMove(engine)),
+ export: m(handleAssetsExport(engine)),
+ probe: q(handleAssetProbe(engine)),
+ frame: q(handleAssetFrame(engine)),
+ transcribe: q(handleAssetTranscribe(engine)),
+ visualize: q(handleAssetVisualize(engine)),
+ analyze: q(requireAuth(handleAssetAnalyze(engine))),
+ }),
+ folder: t.router({
+ list: q(handleFoldersList(engine)),
+ create: m(handleFolderCreate(engine)),
+ rename: m(handleFolderRename(engine)),
+ move: m(handleFoldersMove(engine)),
+ delete: m(handleFoldersDelete(engine)),
+ }),
+ selection: t.router({
+ list: q0(handleSelectionList(engine)),
+ set: m(handleSelectionSet(engine)),
+ focus: m0(handleSelectionFocus(engine)),
+ }),
+ node: t.router({
+ list: q(handleNodeList(engine)),
+ tree: q(handleNodeTree(engine)),
+ grep: q(handleNodeGrep(engine)),
+ screenshot: q(handleNodeScreenshot(engine)),
+ insert: m(handleNodeInsert(engine)),
+ delete: m(handleNodeDelete(engine)),
+ patch: m(handleNodePatch(engine)),
+ duplicate: m(handleNodeDuplicate(engine)),
+ render: m(handleNodeRender(engine)),
+ }),
+ project: t.router({
+ active: q0(handleProjectActive(engine)),
+ list: q0(handleProjectList()),
+ create: m(handleProjectCreate(engine, setParams)),
+ delete: m(handleProjectDelete(engine, setParams)),
+ open: m(handleProjectOpen(engine, setParams)),
+ }),
+ });
+}
+
+export type AppRouter = ReturnType<typeof createAppRouter>;
diff --git a/apps/web/src/lib/cli-rpc.ts b/apps/web/src/lib/cli-rpc.ts
new file mode 100644
index 00000000..dbaf1e12
--- /dev/null
+++ b/apps/web/src/lib/cli-rpc.ts
@@ -0,0 +1,45 @@
+/* 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 { initTRPC } from "@trpc/server";
+import type { AnyTRPCRouter } from "@trpc/server";
+import type { ProcedureCaller, RouterCaller } from "./ipc";
+
+// tRPC instance for the CLI-facing routers. Procedures close over their
+// dependencies (engine, session), so there is no request context. The
+// renderer IS the server here, so opt out of tRPC's browser guard.
+export const t = initTRPC.create({ allowOutsideOfServer: true });
+
+// Inputs come pre-typed from the tRPC client, so parsers are identity casts
+// rather than schemas; validation stays where it always was, in the handlers.
+const input =
+ <I,>() =>
+ (value: unknown) =>
+ value as I;
+
+// Lift an existing unary handler into a procedure, inferring its input and
+// output types. The cast collapses tRPC's conditional input type, which
+// stays unresolved for a generic I. Zero-argument handlers use q0/m0: they
+// skip .input() so the client can call them without an argument.
+export const q = <O, I>(fn: (data: I) => O | Promise<O>) =>
+ t.procedure.input(input<I>()).query(({ input: data }) => fn(data as I));
+
+export const m = <O, I>(fn: (data: I) => O | Promise<O>) =>
+ t.procedure.input(input<I>()).mutation(({ input: data }) => fn(data as I));
+
+export const q0 = <O,>(fn: () => O | Promise<O>) => t.procedure.query(() => fn());
+
+export const m0 = <O,>(fn: () => O | Promise<O>) => t.procedure.mutation(() => fn());
+
+// Adapts a router for the CLI bridge: resolve a dot-joined procedure path to
+// an invocable, or undefined when this router doesn't own the path (the
+// bridge then tries other routers or holds the request).
+export function createRouterCaller(router: AnyTRPCRouter): RouterCaller {
+ const caller = t.createCallerFactory(router)({});
+ return (path: string): ProcedureCaller | undefined => {
+ if (!(path in router._def.procedures)) return undefined;
+ return (data: unknown) =>
+ path.split(".").reduce<any>((o, key) => o[key], caller)(data) as Promise<unknown>;
+ };
+}
diff --git a/apps/web/src/lib/ipc.ts b/apps/web/src/lib/ipc.ts
index 1136e41e..e75948d1 100644
--- a/apps/web/src/lib/ipc.ts
+++ b/apps/web/src/lib/ipc.ts
@@ -12,19 +12,16 @@ import type {
MainRequestChannel,
MainRequestMap,
} from "@desktop/main-channels";
-import { CLI_CHANNELS, CLI_WIRE } from "@diffusionstudio/cli/channels";
-import type {
- CliReply,
- CliRequest,
- CliRequestChannel,
- CliRequestMap,
-} from "@diffusionstudio/cli/channels";
+import { CLI_WIRE } from "@diffusionstudio/cli/channels";
+import type { CliHandshake, CliReply, CliRequest } from "@diffusionstudio/cli/channels";
type EventHandler<C extends MainEventChannel> = (data: MainEventMap[C]) => void;
-type CliHandler<C extends CliRequestChannel> = (
- data: CliRequestMap[C]["request"],
-) => CliRequestMap[C]["response"] | Promise<CliRequestMap[C]["response"]>;
+export type ProcedureCaller = (input: unknown) => Promise<unknown>;
+
+// Resolves a dot-joined tRPC procedure path to an invocable, or undefined
+// when the router doesn't own that path.
+export type RouterCaller = (path: string) => ProcedureCaller | undefined;
type Pending = {
resolve: (value: unknown) => void;
@@ -98,73 +95,73 @@ class MainBridge {
export const mainBridge = new MainBridge();
-// CLI bridge — answers forwarded CLI requests. Main is opaque to channel names
-// here; it just delivers FORWARD_REQ envelopes and routes our FORWARD_REPLY
-// back to the originating socket by id. Requests for channels whose handler
-// isn't registered yet are queued per-channel and drained on the first
-// `handle()` call — this is how we wait for handlers that mount lazily
-// (e.g. asset/project handlers that only register after sign-in) without an
-// explicit ready signal.
+type PendingCliRequest = { req: CliRequest; ws: WebSocket };
+
+// CLI bridge — answers CLI requests. Each CLI command hosts a short-lived
+// WebSocket server; main relays only the connect info (CLI_WIRE.CONNECT) and
+// we dial the CLI directly, so payloads never pass through main. One request
+// and one reply per connection. The bridge is transport-only: the tRPC
+// router registers as a path resolver, and requests arriving before it
+// mounts (or between remounts on project switches) are held and retried on
+// the next registration — no explicit ready signal needed.
class CliBridge {
- private handlers = new Map<CliRequestChannel, CliHandler<CliRequestChannel>>();
- private queue = new Map<CliRequestChannel, CliRequest[]>();
+ private router: RouterCaller | null = null;
+ private pending: PendingCliRequest[] = [];
constructor() {
- // Built-in: lets `waitForCliSocket` probe the round-trip without depending
- // on any app-level handler being registered.
- this.handlers.set(CLI_CHANNELS.PING, (() => undefined) as CliHandler<CliRequestChannel>);
-
- // Bind eagerly so FORWARD_REQ arrivals during page bootstrap are caught
- // rather than silently dropped before any handler registers.
+ // Bind eagerly so CONNECT arrivals during page bootstrap are caught
+ // rather than silently dropped before any router registers.
if (window.desktop) {
- window.desktop.on(CLI_WIRE.FORWARD_REQ, (payload) => {
- void this.dispatch(payload as CliRequest);
+ window.desktop.on(CLI_WIRE.CONNECT, (payload) => {
+ const { port, token } = payload as CliHandshake;
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/?token=${token}`);
+ ws.onmessage = (event) => {
+ try {
+ const req = JSON.parse(event.data as string) as CliRequest;
+ void this.dispatch({ req, ws });
+ } catch (err) {
+ console.error("[cli-bridge] malformed CLI request", err);
+ ws.close();
+ }
+ };
});
}
}
- private async dispatch(req: CliRequest): Promise<void> {
- const handler = this.handlers.get(req.channel);
- if (!handler) {
- let q = this.queue.get(req.channel);
- if (!q) {
- q = [];
- this.queue.set(req.channel, q);
- }
- q.push(req);
+ private async dispatch(pending: PendingCliRequest): Promise<void> {
+ const { req, ws } = pending;
+ const proc = this.router?.(req.path);
+ if (!proc) {
+ this.pending.push(pending);
return;
}
let reply: CliReply;
try {
- const data = await handler(req.data as never);
- reply = { id: req.id, ok: true, data };
+ const data = await proc(req.input);
+ reply = { ok: true, data };
} catch (err) {
- reply = { id: req.id, ok: false, error: (err as Error).message };
+ reply = { ok: false, error: (err as Error).message };
}
try {
- window.desktop?.send(CLI_WIRE.FORWARD_REPLY, reply);
+ ws.send(JSON.stringify(reply));
} catch (err) {
- window.desktop?.send(CLI_WIRE.FORWARD_REPLY, {
- id: req.id,
- ok: false,
- error: `Failed to serialize reply for ${req.channel}: ${(err as Error).message}`,
- });
+ ws.send(
+ JSON.stringify({
+ ok: false,
+ error: `Failed to serialize reply for ${req.path}: ${(err as Error).message}`,
+ }),
+ );
}
}
- handle<C extends CliRequestChannel>(channel: C, handler: CliHandler<C>): () => void {
+ register(router: RouterCaller): () => void {
if (!window.desktop) return () => {};
- const stored = handler as unknown as CliHandler<CliRequestChannel>;
- this.handlers.set(channel, stored);
- const queued = this.queue.get(channel);
- if (queued) {
- this.queue.delete(channel);
- for (const req of queued) void this.dispatch(req);
- }
+ this.router = router;
+ const held = this.pending;
+ this.pending = [];
+ for (const pending of held) void this.dispatch(pending);
return () => {
- if (this.handlers.get(channel) === stored) {
- this.handlers.delete(channel);
- }
+ if (this.router === router) this.router = null;
};
}
}
diff --git a/package-lock.json b/package-lock.json
index 22e1a55f..dae2bb4d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,9 +20,12 @@
"dependencies": {
"@babel/core": "^7.29.7",
"@babel/preset-typescript": "^7.27.1",
+ "@trpc/client": "^11.18.0",
+ "@trpc/server": "^11.18.0",
"babel-preset-solid": "^1.9.12",
"commander": "^14.0.3",
- "esbuild": "^0.28.1"
+ "esbuild": "^0.28.1",
+ "ws": "^8.18.3"
},
"bin": {
"dapi": "dist/index.js"
@@ -30,6 +33,7 @@
"devDependencies": {
"@types/babel__core": "^7.20.5",
"@types/node": "^24.10.1",
+ "@types/ws": "^8.18.1",
"typescript": "~5.9.3"
}
},
@@ -69,6 +73,7 @@
"@supabase/supabase-js": "^2.99.2",
"@tailwindcss/vite": "^4.1.18",
"@trpc/client": "^11.10.0",
+ "@trpc/server": "^11.10.0",
"animejs": "^4.4.1",
"bitecs": "^0.4.0",
"cmdk-solid": "^1.1.2",
@@ -4048,6 +4053,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/yauzl": {
"version": "2.10.3",
"resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
@@ -11466,6 +11481,27 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/ws": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",