The VS Code of video editing, built for agents.
TypeScript
Refactor setup and agent connection logic
konstantin-paulusac10ecca25b2
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex fa2a18eb..22995f0d 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -33,10 +33,7 @@ export const MAIN_CHANNELS = {APP_SHOW_IN_FOLDER: "app:show-in-folder",AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",- CLI_IS_INSTALLED: "cli:is-installed",- CLI_INSTALL: "cli:install",- MCP_IS_REGISTERED: "mcp:is-registered",- MCP_REGISTER: "mcp:register",+ SETUP_ENSURE: "setup:ensure",WINDOW_IS_FULLSCREEN: "window:is-fullscreen",WINDOW_CAPTURE: "window:capture",FILE_TRANSFER: "file:transfer",@@ -141,6 +138,25 @@ export type McpRegisterResult =}| { status: "error"; error: string };+/**+ * What to do about the `dapi` symlink, the one setup step that needs an+ * admin password: `skip` never asks, `auto` asks once and remembers a+ * refusal, `force` asks because the user just asked for it.+ */+export type CliMode = "skip" | "auto" | "force";++/** `present` was already linked; `skipped` was not attempted this run. */+export type CliSetupResult = CliInstallResult | { status: "present" } | { status: "skipped" };++// The state of this machine after `ensureSetup`: where each agent's config+// points, what became of the CLI symlink, and which stale skill directories+// were cleared out (usually none, after the first run that finds them).+export type SetupResult = {+ mcp: McpRegisterResult;+ cli: CliSetupResult;+ skills: string[];+};+export type { SourceEdit, WriteResult };export type MainChannel = (typeof MAIN_CHANNELS)[keyof typeof MAIN_CHANNELS];@@ -168,10 +184,7 @@ export type MainRequestMap = {request: void;response: string | null;};- [MAIN_CHANNELS.CLI_IS_INSTALLED]: { request: void; response: boolean };- [MAIN_CHANNELS.CLI_INSTALL]: { request: void; response: CliInstallResult };- [MAIN_CHANNELS.MCP_IS_REGISTERED]: { request: void; response: boolean };- [MAIN_CHANNELS.MCP_REGISTER]: { request: void; response: McpRegisterResult };+ [MAIN_CHANNELS.SETUP_ENSURE]: { request: void; response: SetupResult };[MAIN_CHANNELS.WINDOW_IS_FULLSCREEN]: { request: void; response: boolean };[MAIN_CHANNELS.WINDOW_CAPTURE]: { request: void; response: ScreenshotResult };[MAIN_CHANNELS.FILE_TRANSFER]: {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 72c6ec6e..15b60ebd 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -12,8 +12,7 @@ import { updateElectronApp } from "update-electron-app";import { DapiServer } from "./dapi/server";import { enableHeadless, isHeadless } from "./headless";import { agentLaunchUrl, listAgents } from "./agent-detect";-import { installCli, isCliInstalled } from "./cli-install";-import { healMcpRegistrations, isMcpRegistered, registerMcp } from "./mcp-install";+import { ensureSetup } from "./setup";import { trackInstall } from "./analytics";import { setupAppMenu } from "./menu";import { mainBridge } from "./main-manager";@@ -293,10 +292,7 @@ if (app.requestSingleInstanceLock()) {});mainBridge.handle(MAIN_CHANNELS.APP_OPEN_EXTERNAL, ({ url }) => shell.openExternal(url));mainBridge.handle(MAIN_CHANNELS.APP_SHOW_IN_FOLDER, ({ path }) => shell.showItemInFolder(path));- mainBridge.handle(MAIN_CHANNELS.CLI_IS_INSTALLED, () => isCliInstalled());- mainBridge.handle(MAIN_CHANNELS.CLI_INSTALL, () => installCli());- mainBridge.handle(MAIN_CHANNELS.MCP_IS_REGISTERED, () => isMcpRegistered());- mainBridge.handle(MAIN_CHANNELS.MCP_REGISTER, () => registerMcp());+ mainBridge.handle(MAIN_CHANNELS.SETUP_ENSURE, () => ensureSetup({ cli: "auto" }));mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () =>takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),);@@ -396,7 +392,8 @@ if (app.requestSingleInstanceLock()) {if (url) deliverDeepLink(url);dapi.start();- healMcpRegistrations();+ // Setup as far as it goes without a password prompt+ ensureSetup({ cli: "skip" });trackInstall();createWindow(!isHiddenLaunch(process.argv));});diff --git a/apps/desktop/src/mcp-install.ts b/apps/desktop/src/mcp-install.tsindex b37d8400..f9a2c339 100644--- a/apps/desktop/src/mcp-install.ts+++ b/apps/desktop/src/mcp-install.ts@@ -58,13 +58,12 @@ function targetAgents(): AgentTarget[] {return present.length > 0 ? present : [FALLBACK_TARGET];}-/** True when at least one agent's config points at this app. */-export function isMcpRegistered(): boolean {- const current = spec();- return AGENT_TARGETS.some((target) => {- const registered = readServer(readConfig(target), target.format);- return registered?.url === current.url || (current.command !== "" && registered?.command === current.command);- });+/** Whether this agent's config already points at exactly what we would write. */+function upToDate(target: AgentTarget, current: McpServerSpec): boolean {+ const registered = readServer(readConfig(target), target.format);+ if (!registered) return false;+ const entry = target.entry(current);+ return typeof entry.command === "string" ? registered.command === entry.command : registered.url === current.url;}export function registerMcp(): McpRegisterResult {@@ -84,6 +83,10 @@ export function registerMcp(): McpRegisterResult {failures.push(`${target.label}: needs the dapi binary, which this build does not have`);continue;}+ if (upToDate(target, current)) {+ agents.push(target.label);+ continue;+ }try {writeConfig(target, upsertServer(readConfig(target), target.format, target.entry(current)));agents.push(target.label);diff --git a/apps/desktop/src/menu.ts b/apps/desktop/src/menu.tsindex 3893344a..32a52d4b 100644--- a/apps/desktop/src/menu.ts+++ b/apps/desktop/src/menu.ts@@ -5,45 +5,54 @@import { app, dialog, Menu } from "electron";import type { MenuItemConstructorOptions } from "electron";-import { CLI_LINK_PATH, installCli } from "./cli-install";-import { registerMcp } from "./mcp-install";+import { CLI_LINK_PATH } from "./cli-install";+import { ensureSetup } from "./setup";-async function registerMcpFromMenu() {- const result = registerMcp();- if (result.status === "registered") {- await dialog.showMessageBox({- type: "info",- message: "Diffusion Studio is registered as an MCP server.",- detail: [- `Connected: ${result.agents.join(", ")}. Restart the agent to pick it up.`,- `Any other agent can use the URL ${result.url}${result.command ? `, or run "${result.command}" over stdio` : ""}.`,- ].join("\n\n"),- });- } else {- await dialog.showMessageBox({- type: "error",- message: "Could not register the MCP server.",- detail: result.error,- });+import type { CliSetupResult } from "./main-channels";++/** The line the dialog gets about the CLI, or null when there is nothing to say. */+function cliDetail(result: CliSetupResult): string | null {+ switch (result.status) {+ case "installed":+ return `The dapi command line tool is linked at ${CLI_LINK_PATH}. Run "dapi --help" to get started.`;+ case "present":+ return `The dapi command line tool is already installed at ${CLI_LINK_PATH}.`;+ case "cancelled":+ return "The dapi command line tool was not installed — the admin prompt was dismissed.";+ case "error":+ return `The dapi command line tool could not be installed: ${result.error}`;+ case "skipped":+ return null;}}-async function installCliFromMenu() {- const result = await installCli();- if (result.status === "cancelled") return;- if (result.status === "installed") {- await dialog.showMessageBox({- type: "info",- message: "The dapi command line tool was installed.",- detail: `Linked at ${CLI_LINK_PATH}. Run "dapi --help" in a terminal to get started.`,- });- } else {+// The menu item behind everything in `setup.ts`. Picking it is asking for+// the CLI by name, so this is the one caller that asks for the password+// again after a previous refusal.+async function connectAgentsFromMenu() {+ const { mcp, cli, skills } = await ensureSetup({ cli: "force" });++ if (mcp.status === "error") {await dialog.showMessageBox({type: "error",- message: "Could not install the dapi command line tool.",- detail: result.error,+ message: "Could not connect your agents.",+ detail: mcp.error,});+ return;}++ const detail = [+ `Connected: ${mcp.agents.join(", ")}. Restart the agent to pick it up.`,+ `Any other agent can use the URL ${mcp.url}${mcp.command ? `, or run "${mcp.command}" over stdio` : ""}.`,+ cliDetail(cli),+ skills.length > 0 ? `Removed ${skills.length} outdated skill folder${skills.length > 1 ? "s" : ""}; the same guidance now comes from the MCP server.` : null,+ ].filter((line): line is string => line !== null);++ await dialog.showMessageBox({+ type: "info",+ message: "Your agents are connected.",+ detail: detail.join("\n\n"),+ });}export function setupAppMenu() {@@ -56,13 +65,8 @@ export function setupAppMenu() {{ role: "about" },{ type: "separator" },{- label: "Connect Agents (MCP)…",- click: registerMcpFromMenu,- },- {- label: "Install dapi Command Line Tool…",- enabled: app.isPackaged,- click: installCliFromMenu,+ label: "Connect Agents…",+ click: connectAgentsFromMenu,},{ type: "separator" },{ role: "services" },diff --git a/apps/desktop/src/setup.ts b/apps/desktop/src/setup.tsnew file mode 100644index 00000000..a6e3233d--- /dev/null+++ b/apps/desktop/src/setup.ts@@ -0,0 +1,67 @@+/* 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 { app } from "electron";+import { existsSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { installCli, isCliInstalled } from "./cli-install";+import { healMcpRegistrations, registerMcp } from "./mcp-install";+import { pruneLegacySkills } from "./skills-cleanup";++import type { CliMode, CliSetupResult, SetupResult } from "./main-channels";++// Linking the CLI needs an admin password, so a refusal has to be+// remembered: asking again on the next handoff is how a prompt turns into+// nagging. Only `force` — the user picking the menu item — asks again.+const DECLINED_FILE = "cli-install-declined";++const declinedPath = (): string => join(app.getPath("userData"), DECLINED_FILE);++function rememberDecline(declined: boolean): void {+ try {+ if (declined) writeFileSync(declinedPath(), "");+ else rmSync(declinedPath(), { force: true });+ } catch {+ // best effort — at worst the prompt comes back, or does not+ }+}++async function ensureCli(mode: CliMode): Promise<CliSetupResult> {+ if (isCliInstalled()) {+ return { status: "present" };+ }+ if (mode === "skip") {+ return { status: "skipped" };+ }+ // Only a packaged build has a binary to link; in dev the symlink is+ // `npm run symlink:create`, so an automatic attempt would only ever fail.+ if (mode === "auto" && (!app.isPackaged || existsSync(declinedPath()))) {+ return { status: "skipped" };+ }++ const result = await installCli();+ if (result.status !== "error") {+ rememberDecline(result.status === "cancelled");+ }+ return result;+}++/**+ * Brings this machine to the state an agent needs, and reports what it+ * found. Only `mcp` is worth failing over: without the config entry the+ * agent opens with no way to reach the app, while a missing `dapi` on PATH+ * costs the user a shell command and nothing else.+ *+ * `cli` says what to do about the symlink, which is the one step that can+ * put a password prompt on screen: `skip` at launch, `auto` before a+ * handoff (asks once, then respects a refusal), `force` when the user asked+ * for it by name.+ */+export async function ensureSetup({ cli = "auto" }: { cli?: CliMode } = {}): Promise<SetupResult> {+ const skills = pruneLegacySkills();+ healMcpRegistrations();+ const mcp = registerMcp();+ return { mcp, cli: await ensureCli(cli), skills };+}diff --git a/apps/desktop/src/skills-cleanup.ts b/apps/desktop/src/skills-cleanup.tsnew file mode 100644index 00000000..36918f4d--- /dev/null+++ b/apps/desktop/src/skills-cleanup.ts@@ -0,0 +1,77 @@+/* 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/. */++// Removes the skill directories older builds planted in agents' skill+// folders. The guidance they carried is served over MCP now (see+// `dapi/knowledge.ts`), so a copy on disk is a second, staler answer to the+// same question — and it points at a `dapi` binary that may no longer be+// where it was linked.+//+// Two kinds were ever installed: real directories copied by the skills CLI+// (`npx skills add diffusionstudio/skills`), and symlinks into the app+// bundle's staged copy. Both go, and nothing else does: a directory has to+// name itself as ours before it is touched.++import { lstatSync, readFileSync, readlinkSync, rmSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import { AGENT_TARGETS } from "./mcp-config";++/** The skills we shipped, by the directory name they were installed under. */+const LEGACY_SKILLS = ["editor", "watch"];++/**+ * Where an agent keeps its global skills: `skills/` beside the marker that+ * says it is set up here — `~/.claude/skills`, `~/.codex/skills`, and so on.+ * Claude Desktop has no such folder, so the path simply never exists.+ */+const skillsDirs = (): string[] =>+ AGENT_TARGETS.map((target) => join(homedir(), target.marker, "skills"));++/** The link's target, or null when `path` is missing or not a symlink. */+function linkTarget(path: string): string | null {+ try {+ return lstatSync(path).isSymbolicLink() ? readlinkSync(path) : null;+ } catch {+ return null;+ }+}++/**+ * Whether the skill at `path` is one of ours. A symlink into a Diffusion+ * Studio bundle is ours even when it dangles — that is the case the app+ * moving leaves behind. Anything else has to say so in its own SKILL.md,+ * which is what keeps a user's unrelated `editor` skill safe.+ */+function isOurs(path: string, name: string): boolean {+ const target = linkTarget(path);+ if (target?.includes("Diffusion Studio") || target?.includes("/AppTranslocation/")) return true;+ try {+ const text = readFileSync(join(path, "SKILL.md"), "utf8");+ return text.includes(`name: ${name}`) && text.includes("Diffusion Studio");+ } catch {+ return false; // no SKILL.md to vouch for it+ }+}++/**+ * Removes every stale skill of ours from the agents we support, and returns+ * the paths it removed. Best effort: a skill it cannot read or delete is+ * left where it is. Removing a symlink removes the link, never its target.+ */+export function pruneLegacySkills(): string[] {+ const removed: string[] = [];+ for (const dir of skillsDirs()) {+ for (const name of LEGACY_SKILLS) {+ const path = join(dir, name);+ if (!isOurs(path, name)) continue;+ try {+ rmSync(path, { recursive: true, force: true });+ removed.push(path);+ } catch { /* Ignore errors */ }+ }+ }+ return removed;+}diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsxindex ca3986ee..a18dc783 100644--- a/apps/web/src/components/dashboard/home-view.tsx+++ b/apps/web/src/components/dashboard/home-view.tsx@@ -42,7 +42,7 @@ import { projectRoute } from "@/hooks/use-project-route";import { store } from "@/init";import {agentIcon,- connectAgents,+ ensureAgentSetup,launchAgent,listAgents,type AgentInfo,@@ -199,7 +199,7 @@ export function DashboardHomeView() {// Before anything else: the agent is no use on this project without the// app's MCP server in its config, and it reads that config at startup —// so it has to be there before the link opens it.- await connectAgents();+ await ensureAgentSetup();const project = await resolveTarget();if (!project) return;diff --git a/apps/web/src/lib/agents.ts b/apps/web/src/lib/agents.tsindex ae8bcc17..efe2a108 100644--- a/apps/web/src/lib/agents.ts+++ b/apps/web/src/lib/agents.ts@@ -55,16 +55,20 @@ export async function launchAgent(}/**- * Points the agents on this machine at this app's MCP server, unless one- * already is. Without it the agent opens with the prompt but has no way to- * touch the project, so this runs before the prompt is handed over rather- * than at some quieter moment — and it throws when it cannot, because- * carrying on would send the agent off without its tools.+ * Brings this machine to the state the agent needs: its config pointing at+ * this app's MCP server, the `dapi` CLI on PATH, and no stale skills left+ * over from older builds. Main does the work (`setup.ts`) and every step is+ * idempotent, so this runs before each handoff rather than at some quieter+ * moment — the agent reads its config at startup, and the link is what+ * starts it.+ *+ * It throws only when the MCP config could not be written, because that is+ * the one failure that would send the agent off without its tools. The CLI+ * is for the user's own shell, so its outcome is not this path's business.*/-export async function connectAgents(): Promise<void> {+export async function ensureAgentSetup(): Promise<void> {if (!window.desktop) return;- if (await mainBridge.call(MAIN_CHANNELS.MCP_IS_REGISTERED, undefined)) return;- const result = await mainBridge.call(MAIN_CHANNELS.MCP_REGISTER, undefined);- if (result.status === "error") throw new Error(result.error);+ const { mcp } = await mainBridge.call(MAIN_CHANNELS.SETUP_ENSURE, undefined);+ if (mcp.status === "error") throw new Error(mcp.error);}