The VS Code of video editing, built for agents.
TypeScript
Refactor and remove unused CLI and MCP setup functionality
konstantin-paulus1532bf0e3407
diff --git a/apps/desktop/scripts/stage-cli.mjs b/apps/desktop/scripts/stage-cli.mjsindex 0117c593..a774a41e 100644--- a/apps/desktop/scripts/stage-cli.mjs+++ b/apps/desktop/scripts/stage-cli.mjs@@ -5,8 +5,7 @@// Stages the dapi CLI into apps/desktop/cli so electron-forge can ship it as// an app resource (Contents/Resources/cli). The staged layout:// cli/dapi.js bundled CLI (built by apps/cli), self-contained-// cli/bin/dapi shell wrapper: what agents run as `dapi mcp` (registered-// by mcp-install.ts) and the file that gets linked into PATH+// cli/bin/dapi shell wrapper: the file that gets linked into PATHimport { chmodSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";@@ -23,7 +22,7 @@ cpSync(join(cliDir, "dist", "index.js"), join(stageDir, "dapi.js"));// The wrapper runs the CLI bundle on the app's own Electron binary in Node// mode, so users need no separate Node install. It resolves symlinks first-// because both Homebrew and the in-app installer link it into PATH.+// because Homebrew links it into PATH.const wrapper = `#!/bin/shSELF="$0"while [ -L "$SELF" ]; dodiff --git a/apps/desktop/src/cli-install.ts b/apps/desktop/src/cli-install.tsdeleted file mode 100644index 79307ddc..00000000--- a/apps/desktop/src/cli-install.ts+++ /dev/null@@ -1,94 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { app } from "electron";-import { execFile } from "node:child_process";-import { existsSync, lstatSync } from "node:fs";-import { join } from "node:path";-import type { CliInstallResult } from "./main-channels";--// Outcome of taking the symlink back out. "absent" means there was none to-// remove; "cancelled" that the admin prompt was dismissed and it stays.-export type CliUninstallResult =- | { status: "removed" }- | { status: "absent" }- | { status: "cancelled" }- | { status: "error"; error: string };--export const CLI_LINK_PATH = "/usr/local/bin/dapi";--// The dev workflow links the workspace build into Homebrew's bin instead-// (`symlink:create` in apps/cli), so both locations count as installed.-const DEV_LINK_PATH = "/opt/homebrew/bin/dapi";--export function isCliInstalled(): boolean {- return existsSync(CLI_LINK_PATH) || existsSync(DEV_LINK_PATH);-}--/**- * Whether the link this app creates is there — dangling or not, since a- * link left behind by a deleted bundle is exactly what removal is for.- * `existsSync` follows links and would miss that case.- */-export function isCliLinked(): boolean {- return lstatSync(CLI_LINK_PATH, { throwIfNoEntry: false })?.isSymbolicLink() ?? false;-}--// Linking into /usr/local/bin needs elevation; osascript shows the standard-// macOS admin prompt so the app itself never asks for credentials.-function linkCli(): Promise<void> {- const wrapper = join(process.resourcesPath, "cli", "bin", "dapi");- const shell = `mkdir -p /usr/local/bin && ln -sf '${wrapper}' '${CLI_LINK_PATH}'`;- const script = `do shell script "${shell.replaceAll('"', '\\"')}" with administrator privileges`;- return new Promise((resolve, reject) => {- execFile("osascript", ["-e", script], (err) => (err ? reject(err) : resolve()));- });-}--// The same elevation for the removal, with the same prompt.-function unlinkCli(): Promise<void> {- const script = `do shell script "rm -f '${CLI_LINK_PATH}'" with administrator privileges`;- return new Promise((resolve, reject) => {- execFile("osascript", ["-e", script], (err) => (err ? reject(err) : resolve()));- });-}--export async function installCli(): Promise<CliInstallResult> {- if (!app.isPackaged) {- return {- status: "error",- error: "Installing the CLI is only available in the packaged app. Use `npm run symlink:create` in development.",- };- }- try {- await linkCli();- return { status: "installed" };- } catch (e) {- const message = (e as Error).message ?? "";- if (message.includes("-128")) return { status: "cancelled" }; // user cancelled the admin prompt- return { status: "error", error: message };- }-}--/**- * Removes the `dapi` link from PATH. Only the link at {@link CLI_LINK_PATH}- * is touched, and only when it is a symlink: a real binary somebody put- * there is not ours to delete, and the dev link in Homebrew's bin belongs- * to `npm run symlink:remove`.- */-export async function uninstallCli(): Promise<CliUninstallResult> {- const stat = lstatSync(CLI_LINK_PATH, { throwIfNoEntry: false });- if (!stat) return { status: "absent" };- if (!stat.isSymbolicLink()) {- return { status: "error", error: `${CLI_LINK_PATH} is not a link this app created, so it was left alone.` };- }- try {- await unlinkCli();- return { status: "removed" };- } catch (e) {- const message = (e as Error).message ?? "";- if (message.includes("-128")) return { status: "cancelled" }; // user cancelled the admin prompt- return { status: "error", error: message };- }-}diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.tsindex 99b3357d..41b8b8c0 100644--- a/apps/desktop/src/dapi/server.ts+++ b/apps/desktop/src/dapi/server.ts@@ -10,7 +10,6 @@ import { MCP_HOST, MCP_PATH, MCP_PORT, SOCKET_PATH, SocketTransport } from "@difimport { mainHandlers } from "./handlers";import { DapiHttpServer } from "./http";import { instructions, registerPrompts, registerResources } from "./knowledge";-import { SERVER_NAME } from "../mcp-config";import { present, toCallToolResult, toErrorResult } from "./present";import { RendererCalls } from "./renderer-calls";@@ -18,6 +17,13 @@ import type { Server, Socket } from "node:net";import type { GenericTool, LogEntry, ToolName, ToolOutput } from "@diffusionstudio/dapi";import type { MainContext, MainToolName } from "./handler";+/**+ * The name the server introduces itself with, and so the namespace an agent+ * shows us under: `mcp__diffusion__<tool>` and `/diffusion:<prompt>`. The+ * same word as our URL scheme, and not `dapi`, which is the CLI.+ */+const SERVER_NAME = "diffusion";+export type DapiServerDeps = {version: string;/** The app's console buffer, for `logs` and `report`. */diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex fa03af4e..49b043ca 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -31,8 +31,6 @@ 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",- SETUP_ENSURE: "setup:ensure",- SETUP_STATUS: "setup:status",WINDOW_IS_FULLSCREEN: "window:is-fullscreen",WINDOW_CAPTURE: "window:capture",FILE_TRANSFER: "file:transfer",@@ -103,51 +101,6 @@ export type ProjectInfo = {export type CompileResult ={ ok: true; code: string } | { ok: false; error: string };-// Outcome of linking the bundled dapi CLI into PATH. "cancelled" means the-// user dismissed the macOS admin prompt — not an error, not installed.-export type CliInstallResult =- | { status: "installed" }- | { status: "cancelled" }- | { status: "error"; error: string };--// Outcome of registering the app's MCP server with the agents on this-// machine. `agents` names the configs written; `url` is the HTTP endpoint-// most of them got, `command` the stdio proxy the rest run (null when this-// build has no dapi binary).-export type McpRegisterResult =- | {- status: "registered";- agents: string[];- url: string;- command: string | null;- }- | { 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 SetupStatus = {- /** Every agent config on this machine points at this build's MCP server. */- mcp: boolean;- cli: "present" | "missing" | "declined" | "unavailable";-};-export type { SourceEdit, WriteResult };export type MainChannel = (typeof MAIN_CHANNELS)[keyof typeof MAIN_CHANNELS];@@ -170,11 +123,6 @@ export type MainRequestMap = {request: void;response: string | null;};- [MAIN_CHANNELS.SETUP_ENSURE]: {- request: { cli?: CliMode };- response: SetupResult;- };- [MAIN_CHANNELS.SETUP_STATUS]: { request: void; response: SetupStatus };[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 e3a3bc7b..668ea2b9 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -11,9 +11,9 @@ import type { FileHandle } from "node:fs/promises";import { updateElectronApp } from "update-electron-app";import { DapiServer } from "./dapi/server";import { enableHeadless, isHeadless } from "./headless";-import { ensureSetup, setupStatus, verifySetup } from "./setup";+import { pruneLegacySkills } from "./skills-cleanup";import { trackInstall } from "./analytics";-import { refreshAppMenu, setupAppMenu } from "./menu";+import { setupAppMenu } from "./menu";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";import {@@ -285,8 +285,6 @@ 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.SETUP_ENSURE, ({ cli }) => ensureSetup(cli));- mainBridge.handle(MAIN_CHANNELS.SETUP_STATUS, () => setupStatus());mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () =>takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),);@@ -386,8 +384,7 @@ if (app.requestSingleInstanceLock()) {if (url) deliverDeepLink(url);dapi.start();- verifySetup();- refreshAppMenu();+ pruneLegacySkills();trackInstall();createWindow(!isHiddenLaunch(process.argv));});diff --git a/apps/desktop/src/mcp-config.test.ts b/apps/desktop/src/mcp-config.test.tsdeleted file mode 100644index 66132e8a..00000000--- a/apps/desktop/src/mcp-config.test.ts+++ /dev/null@@ -1,145 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { describe, expect, it } from "vitest";-import { AGENT_TARGETS, readServer, removeServer, upsertServer } from "./mcp-config";--const spec = {- url: "http://127.0.0.1:3274/mcp",- command: "/Applications/Diffusion Studio.app/Contents/Resources/cli/bin/dapi",- args: ["mcp"],-};--const target = (label: string) => {- const found = AGENT_TARGETS.find((t) => t.label === label);- if (!found) throw new Error(label);- return found;-};--describe("per-agent entries", () => {- it("spells the URL the way each agent expects", () => {- expect(target("Claude Code").entry(spec)).toEqual({ type: "http", url: spec.url });- expect(target("Cursor").entry(spec)).toEqual({ url: spec.url });- expect(target("Codex").entry(spec)).toEqual({ url: spec.url });- expect(target("Gemini CLI").entry(spec)).toEqual({ httpUrl: spec.url });- expect(target("Windsurf").entry(spec)).toEqual({ serverUrl: spec.url });- });-- it("gives Claude Desktop the stdio proxy", () => {- expect(target("Claude Desktop").entry(spec)).toEqual({ command: spec.command, args: ["mcp"] });- });-});--describe("json configs", () => {- it("creates the file from nothing", () => {- const text = upsertServer(null, "json", { type: "http", url: spec.url });- expect(JSON.parse(text)).toEqual({ mcpServers: { diffusion: { type: "http", url: spec.url } } });- expect(text.endsWith("\n")).toBe(true);- });-- it("keeps other servers and unrelated keys", () => {- const before = JSON.stringify({- numStartups: 12,- mcpServers: { other: { command: "x", args: [] } },- projects: { "/a": { allowedTools: [] } },- });- const after = JSON.parse(upsertServer(before, "json", { url: spec.url }));- expect(after.numStartups).toBe(12);- expect(after.projects).toEqual({ "/a": { allowedTools: [] } });- expect(after.mcpServers.other).toEqual({ command: "x", args: [] });- expect(after.mcpServers.diffusion).toEqual({ url: spec.url });- });-- it("replaces a stdio entry with a URL entry, and reads either", () => {- const before = upsertServer(null, "json", { command: "/old/dapi", args: ["mcp"] });- expect(readServer(before, "json")).toEqual({ command: "/old/dapi" });- const after = upsertServer(before, "json", { type: "http", url: spec.url });- expect(readServer(after, "json")).toEqual({ url: spec.url });- expect(JSON.parse(after).mcpServers.diffusion.command).toBeUndefined();- });-- it("reads the URL under each agent's key", () => {- for (const key of ["url", "httpUrl", "serverUrl"]) {- expect(readServer(upsertServer(null, "json", { [key]: spec.url }), "json")).toEqual({ url: spec.url });- }- });-- it("refuses to overwrite a file it cannot parse", () => {- expect(() => upsertServer("{ not json", "json", { url: spec.url })).toThrow();- expect(() => upsertServer("[1, 2]", "json", { url: spec.url })).toThrow();- expect(readServer("{ not json", "json")).toBeNull();- });-- it("treats an empty file as no config", () => {- expect(readServer("", "json")).toBeNull();- expect(JSON.parse(upsertServer(" \n", "json", { url: spec.url }))).toEqual({ mcpServers: { diffusion: { url: spec.url } } });- });-- it("removes our entry and nothing else", () => {- const before = JSON.stringify({- numStartups: 12,- mcpServers: { other: { command: "x", args: [] }, diffusion: { type: "http", url: spec.url } },- });- const after = removeServer(before, "json");- expect(after).not.toBeNull();- expect(JSON.parse(after as string)).toEqual({ numStartups: 12, mcpServers: { other: { command: "x", args: [] } } });- expect(readServer(after, "json")).toBeNull();- });-- it("has nothing to remove from a config without our entry", () => {- expect(removeServer(null, "json")).toBeNull();- expect(removeServer("", "json")).toBeNull();- expect(removeServer(JSON.stringify({ mcpServers: { other: { url: "u" } } }), "json")).toBeNull();- expect(removeServer("{ not json", "json")).toBeNull();- });-});--describe("toml configs (codex)", () => {- it("appends a table to an existing config", () => {- const before = 'model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n';- const after = upsertServer(before, "toml", { url: spec.url });- expect(after).toBe('model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n\n[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n');- expect(readServer(after, "toml")).toEqual({ url: spec.url });- });-- it("replaces our table in place and leaves the next one alone", () => {- const before = '[mcp_servers.diffusion]\ncommand = "/old/dapi"\nargs = ["mcp"]\n\n[mcp_servers.other]\ncommand = "x"\n';- expect(readServer(before, "toml")).toEqual({ command: "/old/dapi" });- const after = upsertServer(before, "toml", { url: spec.url });- expect(after).toBe('[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n[mcp_servers.other]\ncommand = "x"\n');- expect(readServer(after, "toml")).toEqual({ url: spec.url });- });-- it("starts a file from nothing", () => {- const text = upsertServer(null, "toml", { url: spec.url });- expect(text).toBe('[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n');- });-- it("escapes quotes and backslashes in stdio paths", () => {- const odd = { command: 'C:\\Apps\\"Diffusion"\\dapi', args: ["mcp"] };- const text = upsertServer(null, "toml", odd);- expect(text).toContain('command = "C:\\\\Apps\\\\\\"Diffusion\\"\\\\dapi"');- expect(readServer(text, "toml")).toEqual({ command: odd.command });- });-- it("reads nothing from a config without our table", () => {- expect(readServer('model = "o3"\n', "toml")).toBeNull();- expect(removeServer('model = "o3"\n', "toml")).toBeNull();- });-- it("removes our table from the end of a config", () => {- const before = 'model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n';- const connected = upsertServer(before, "toml", { url: spec.url });- expect(removeServer(connected, "toml")).toBe(before);- });-- it("removes our table from between others without leaving a gap", () => {- const before = 'model = "o3"\n\n[mcp_servers.diffusion]\nurl = "u"\n\n[mcp_servers.other]\ncommand = "x"\n';- expect(removeServer(before, "toml")).toBe('model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n');- });-- it("empties a config that held only our table", () => {- expect(removeServer(upsertServer(null, "toml", { url: spec.url }), "toml")).toBe("");- });-});diff --git a/apps/desktop/src/mcp-config.ts b/apps/desktop/src/mcp-config.tsdeleted file mode 100644index c49c10aa..00000000--- a/apps/desktop/src/mcp-config.ts+++ /dev/null@@ -1,190 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--// How the app's MCP server is written into each agent's config, as pure-// text transforms: no file system, no Electron, so the merge rules are-// testable. `mcp-install.ts` decides which files and does the I/O.--/**- * The two ways to reach the app. Agents that speak Streamable HTTP get the- * URL, which is the same on every machine; the rest get the bundled `dapi`- * binary in stdio proxy mode.- */-export type McpServerSpec = { url: string; command: string; args: string[] };--/**- * The key our entry lives under in every agent's server map, and so the- * namespace an agent shows us under: `mcp__diffusion__<tool>` and- * `/diffusion:<prompt>`. The same word as our URL scheme, and not `dapi`,- * which is the CLI.- */-export const SERVER_NAME = "diffusion";--/** One agent's config entry: what its file format spells a server as. */-export type ServerEntry = Record<string, string | string[]>;--export type AgentTarget = {- /** Human name, for the result dialog. */- label: string;- /** Home-relative path whose presence means the agent is set up on this machine. */- marker: string;- /** Home-relative path of the config file our entry goes into. */- config: string;- format: "json" | "toml";- /** The entry for this agent: which transport it gets, under the keys its format uses. */- entry(spec: McpServerSpec): ServerEntry;-};--const http = (key: string, extra: ServerEntry = {}) => (spec: McpServerSpec): ServerEntry => ({ ...extra, [key]: spec.url });-const stdio = (spec: McpServerSpec): ServerEntry => ({ command: spec.command, args: [...spec.args] });--// Agents whose MCP config we know how to write. Claude Code's user scope is-// the top-level `mcpServers` of ~/.claude.json, the same file `claude mcp-// add --scope user` edits. Claude Desktop's file takes stdio commands only,-// so it gets the proxy.-export const AGENT_TARGETS: readonly AgentTarget[] = [- { label: "Claude Code", marker: ".claude", config: ".claude.json", format: "json", entry: http("url", { type: "http" }) },- { label: "Codex", marker: ".codex", config: ".codex/config.toml", format: "toml", entry: http("url") },- { label: "Cursor", marker: ".cursor", config: ".cursor/mcp.json", format: "json", entry: http("url") },- { label: "Gemini CLI", marker: ".gemini", config: ".gemini/settings.json", format: "json", entry: http("httpUrl") },- { label: "Windsurf", marker: ".codeium/windsurf", config: ".codeium/windsurf/mcp_config.json", format: "json", entry: http("serverUrl") },- {- label: "Claude Desktop",- marker: "Library/Application Support/Claude",- config: "Library/Application Support/Claude/claude_desktop_config.json",- format: "json",- entry: stdio,- },-];--/** The agent a machine with none of the above still gets set up for. */-export const FALLBACK_TARGET = AGENT_TARGETS[0];--/**- * The config with our entry set, leaving everything else as it was. `text`- * is the file's current content, or null when there is none yet. Throws- * when the file cannot be parsed: a config we cannot read is not one we- * should overwrite.- */-export function upsertServer(text: string | null, format: AgentTarget["format"], entry: ServerEntry): string {- return format === "toml" ? upsertToml(text, entry) : upsertJson(text, entry);-}--/**- * The config with our entry taken out, everything else untouched; null when- * the file has no entry of ours (or cannot be parsed), so there is nothing- * to write back. Other servers and unrelated keys stay as they were.- */-export function removeServer(text: string | null, format: AgentTarget["format"]): string | null {- if (readServer(text, format) === null) return null;- return format === "toml" ? removeToml(text as string) : removeJson(text as string);-}--/** Where our entry currently points, whatever keys the agent spells it with; null when there is none. */-export type Registered = { url?: string; command?: string };--export function readServer(text: string | null, format: AgentTarget["format"]): Registered | null {- if (text === null) return null;- const entry = format === "toml" ? readToml(text) : readJson(text);- if (!entry) return null;- const url = entry.url ?? entry.httpUrl ?? entry.serverUrl;- const command = entry.command;- if (typeof url !== "string" && typeof command !== "string") return null;- return {- ...(typeof url === "string" ? { url } : {}),- ...(typeof command === "string" ? { command } : {}),- };-}--// --- JSON --------------------------------------------------------------------type JsonConfig = { mcpServers?: Record<string, unknown> } & Record<string, unknown>;--function parseJson(text: string | null): JsonConfig {- if (text === null || text.trim() === "") return {};- const parsed: unknown = JSON.parse(text);- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {- throw new Error("expected a JSON object at the top level");- }- return parsed as JsonConfig;-}--function upsertJson(text: string | null, entry: ServerEntry): string {- const config = parseJson(text);- const servers = typeof config.mcpServers === "object" && config.mcpServers !== null ? config.mcpServers : {};- config.mcpServers = { ...servers, [SERVER_NAME]: entry };- return `${JSON.stringify(config, null, 2)}\n`;-}--function removeJson(text: string): string {- const config = parseJson(text);- const { [SERVER_NAME]: _ours, ...servers } = config.mcpServers ?? {};- config.mcpServers = servers;- return `${JSON.stringify(config, null, 2)}\n`;-}--function readJson(text: string): Record<string, unknown> | null {- let config: JsonConfig;- try {- config = parseJson(text);- } catch {- return null;- }- const entry = config.mcpServers?.[SERVER_NAME];- return typeof entry === "object" && entry !== null ? (entry as Record<string, unknown>) : null;-}--// --- TOML (Codex) ------------------------------------------------------------// Our table, from its header up to the next table header or the end. A-// header line is `[...]` at column 0; indented or commented ones are not.-const TOML_TABLE = new RegExp(String.raw`^\[mcp_servers\.${SERVER_NAME}\][^\n]*\n(?:(?!\[)[^\n]*\n?)*`, "m");--function tomlString(value: string): string {- return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;-}--function tomlValue(value: string | string[]): string {- return Array.isArray(value) ? `[${value.map(tomlString).join(", ")}]` : tomlString(value);-}--function tomlTable(entry: ServerEntry): string {- const lines = Object.entries(entry).map(([key, value]) => `${key} = ${tomlValue(value)}`);- return [`[mcp_servers.${SERVER_NAME}]`, ...lines, ""].join("\n");-}--function upsertToml(text: string | null, entry: ServerEntry): string {- const current = text ?? "";- const table = tomlTable(entry);- if (TOML_TABLE.test(current)) return current.replace(TOML_TABLE, table);- const separator = current === "" || current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n";- return `${current}${separator}${table}`;-}--// Drops our table, then the blank lines it used to sit between so the file-// does not end in (or contain) a growing gap after a connect/disconnect cycle.-function removeToml(text: string): string {- const rest = text.replace(TOML_TABLE, "").replace(/\n{3,}/g, "\n\n").trimEnd();- return rest === "" ? "" : `${rest}\n`;-}--function readToml(text: string): Record<string, unknown> | null {- const table = text.match(TOML_TABLE)?.[0];- if (!table) return null;- const entry: Record<string, unknown> = {};- for (const line of table.split("\n").slice(1)) {- const scalar = line.match(/^(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/);- if (scalar) {- entry[scalar[1]] = untomlString(scalar[2]);- continue;- }- const list = line.match(/^(\w+)\s*=\s*\[([^\]]*)\]\s*$/);- if (list) entry[list[1]] = [...list[2].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => untomlString(m[1]));- }- return entry;-}--function untomlString(value: string): string {- return value.replaceAll('\\"', '"').replaceAll("\\\\", "\\");-}diff --git a/apps/desktop/src/mcp-install.ts b/apps/desktop/src/mcp-install.tsdeleted file mode 100644index 0980f604..00000000--- a/apps/desktop/src/mcp-install.ts+++ /dev/null@@ -1,182 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--// Registers the app's MCP server with the agents on this machine: the fixed-// loopback URL for agents that speak HTTP, the bundled `dapi mcp` proxy for-// the rest. No PATH symlink and no admin prompt — the counterpart of the-// shell install in `cli-install.ts`, which stays for people who type `dapi`.--import { app } from "electron";-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { homedir } from "node:os";-import { dirname, join } from "node:path";-import { MCP_URL } from "@diffusionstudio/dapi/socket";-import { AGENT_TARGETS, FALLBACK_TARGET, readServer, removeServer, upsertServer } from "./mcp-config";--import type { AgentTarget, McpServerSpec } from "./mcp-config";-import type { McpRegisterResult } from "./main-channels";--/** What `unregisterMcp` did: the agents whose entry was removed, and the configs it could not rewrite. */-export type McpUnregisterResult = { agents: string[]; failures: string[] };--// The dev workflow links the workspace build into Homebrew's bin-// (`symlink:create` in apps/cli); that is the binary a dev build registers.-const DEV_BINARY = "/opt/homebrew/bin/dapi";--/** The bundled `dapi` binary, or null when none is available (an unstaged dev build). */-export function dapiBinary(): string | null {- const command = app.isPackaged ? join(process.resourcesPath, "cli", "bin", "dapi") : DEV_BINARY;- return existsSync(command) ? command : null;-}--function spec(): McpServerSpec {- return { url: MCP_URL, command: dapiBinary() ?? "", args: ["mcp"] };-}--function configPath(target: AgentTarget): string {- return join(homedir(), target.config);-}--function readConfig(target: AgentTarget): string | null {- const path = configPath(target);- return existsSync(path) ? readFileSync(path, "utf8") : null;-}--function writeConfig(target: AgentTarget, text: string): void {- const path = configPath(target);- mkdirSync(dirname(path), { recursive: true });- writeFileSync(path, text);-}--function needsBinary(target: AgentTarget): boolean {- return "command" in target.entry({ url: MCP_URL, command: "x", args: [] });-}--// Agents present on this machine, falling back to Claude Code so a machine-// with no agent yet still gets set up for the primary one.-function targetAgents(): AgentTarget[] {- const home = homedir();- const present = AGENT_TARGETS.filter((target) => existsSync(join(home, target.marker)));- return present.length > 0 ? present : [FALLBACK_TARGET];-}--/** 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;-}--/**- * Whether every agent config this machine needs already points at this build.- */-export function mcpRegistered(): boolean {- const current = spec();- const reachable = targetAgents()- .filter((target) => !(needsBinary(target) && current.command === ""));- return reachable.length > 0 && reachable.every((target) => upToDate(target, current));-}--export function registerMcp(): McpRegisterResult {- // A quarantined first launch runs from a translocated read-only mount whose- // path won't survive the next launch — registering it would dangle.- if (app.isPackaged && process.resourcesPath.includes("/AppTranslocation/")) {- return {- status: "error",- error: "Move Diffusion Studio to the Applications folder and relaunch it, then try again.",- };- }- const current = spec();- const agents: string[] = [];- const failures: string[] = [];- for (const target of targetAgents()) {- if (needsBinary(target) && current.command === "") {- 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);- } catch (e) {- failures.push(`${target.label} (${target.config}): ${(e as Error).message}`);- }- }- if (agents.length === 0) {- return { status: "error", error: `Could not write any agent config:\n${failures.join("\n")}` };- }- return {- status: "registered",- agents,- url: current.url,- command: current.command === "" ? null : `${current.command} ${current.args.join(" ")}`,- };-}--/**- * The agents whose config carries our entry right now, whatever it points- * at: this is what "Disconnect Agents" has to undo, so unlike `targetAgents`- * it looks at every config we know, not only the agents that are installed.- */-export function registeredAgents(): string[] {- return AGENT_TARGETS- .filter((target) => readServer(readConfig(target), target.format) !== null)- .map((target) => target.label);-}--/**- * Takes our entry out of every agent config that has one. The inverse of- * `registerMcp`, and just as narrow: other servers in the same file, the- * `dapi` symlink, and the app's own state are all left alone. The next- * handoff from the dashboard registers again — disconnecting is for a user- * who wants the agent to stop seeing the app until then.- */-export function unregisterMcp(): McpUnregisterResult {- const agents: string[] = [];- const failures: string[] = [];- for (const target of AGENT_TARGETS) {- const text = readConfig(target);- const next = removeServer(text, target.format);- if (next === null) continue;- try {- writeConfig(target, next);- agents.push(target.label);- } catch (e) {- failures.push(`${target.label} (${target.config}): ${(e as Error).message}`);- }- }- return { agents, failures };-}--/**- * Launch-time self-heal. Two cases: an entry that still runs the stdio proxy- * from a bundle that moved (or was translocated when it was written), and an- * entry written before the app served HTTP, which the agent could be using- * the URL for instead. Both are rewritten to what `registerMcp` would write- * today. Entries the user wrote by hand for something else are left alone.- */-export function healMcpRegistrations(): void {- if (!app.isPackaged) return;- const current = spec();- if (current.command === "" || current.command.includes("/AppTranslocation/")) return;-- for (const target of AGENT_TARGETS) {- const text = readConfig(target);- const registered = readServer(text, target.format);- if (!registered?.command) continue;- const ours = registered.command.includes("Diffusion Studio") || registered.command.includes("/AppTranslocation/");- if (!ours) continue;- const entry = target.entry(current);- if (registered.command === entry.command) continue;- try {- writeConfig(target, upsertServer(text, target.format, entry));- } catch {- // best effort — the connect button remains as a manual fix- }- }-}diff --git a/apps/desktop/src/menu.ts b/apps/desktop/src/menu.tsindex d8aaaa3b..25c54e01 100644--- a/apps/desktop/src/menu.ts+++ b/apps/desktop/src/menu.ts@@ -2,142 +2,9 @@* 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, dialog, Menu } from "electron";+import { app, Menu } from "electron";import type { MenuItemConstructorOptions } from "electron";-import { CLI_LINK_PATH, isCliLinked } from "./cli-install";-import { registeredAgents } from "./mcp-install";-import { disconnectSetup, ensureSetup, setupConnected } from "./setup";--import type { CliUninstallResult } from "./cli-install";-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;- }-}--// 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("force");-- if (mcp.status === "error") {- await dialog.showMessageBox({- type: "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"),- });-}--/** The line the disconnect dialog gets about the CLI, or null when there was nothing to remove. */-function cliRemovalDetail(result: CliUninstallResult): string | null {- switch (result.status) {- case "removed":- return `The dapi command line tool was removed from ${CLI_LINK_PATH}.`;- case "cancelled":- return `The dapi command line tool is still at ${CLI_LINK_PATH} — the admin prompt was dismissed.`;- case "error":- return `The dapi command line tool could not be removed: ${result.error}`;- case "absent":- return null;- }-}--// The inverse of the item above: takes the app's MCP entry back out of every-// agent config that has one, and the dapi link off PATH. Reversible from the-// same menu, so a plain confirm is enough; the item is only shown while-// there is something to undo.-async function disconnectAgentsFromMenu() {- const agents = registeredAgents();- const linked = isCliLinked();- if (agents.length === 0 && !linked) {- refreshAppMenu();- return;- }-- const { response } = await dialog.showMessageBox({- type: "question",- message: "Disconnect your agents?",- detail: [- agents.length > 0 ? `Diffusion Studio will be removed from the MCP configuration of ${agents.join(", ")}. Restart the agent to pick it up.` : null,- linked ? `The dapi command line tool will be removed from ${CLI_LINK_PATH}, which needs your admin password.` : null,- "Sending a prompt to an agent from the dashboard connects it again.",- ].filter((line): line is string => line !== null).join("\n\n"),- buttons: ["Disconnect", "Cancel"],- defaultId: 0,- cancelId: 1,- });- if (response !== 0) return;-- const { mcp, cli } = await disconnectSetup();-- const failed = [- ...mcp.failures,- cli.status === "error" ? cli.error : null,- ].filter((line): line is string => line !== null);- const undone = mcp.agents.length > 0 || cli.status === "removed";-- if (!undone) {- await dialog.showMessageBox({- type: cli.status === "cancelled" ? "info" : "error",- message: "Your agents were not disconnected.",- detail: [cliRemovalDetail(cli), ...mcp.failures].filter((line): line is string => line !== null).join("\n\n"),- });- return;- }-- await dialog.showMessageBox({- type: failed.length > 0 || cli.status === "cancelled" ? "warning" : "info",- message: "Your agents are disconnected.",- detail: [- mcp.agents.length > 0 ? `Disconnected: ${mcp.agents.join(", ")}. Restart the agent to pick it up.` : null,- cliRemovalDetail(cli),- mcp.failures.length > 0 ? `Could not update:\n${mcp.failures.join("\n")}` : null,- ].filter((line): line is string => line !== null).join("\n\n"),- });-}--const DISCONNECT_ITEM_ID = "disconnect-agents";--/**- * Re-reads what setup left on this machine and shows or hides "Disconnect- * Agents…" to match. Called after anything that changes it — the two menu- * items, and setup runs the renderer asks for — so the menu never offers to- * undo a connection that is not there.- */-export function refreshAppMenu() {- const item = Menu.getApplicationMenu()?.getMenuItemById(DISCONNECT_ITEM_ID);- if (item) item.visible = setupConnected();-}-export function setupAppMenu() {if (process.platform !== "darwin") return;@@ -147,17 +14,6 @@ export function setupAppMenu() {submenu: [{ role: "about" },{ type: "separator" },- {- label: "Connect Agents…",- click: connectAgentsFromMenu,- },- {- id: DISCONNECT_ITEM_ID,- label: "Disconnect Agents…",- visible: setupConnected(),- click: disconnectAgentsFromMenu,- },- { type: "separator" },{ role: "services" },{ type: "separator" },{ role: "hide" },diff --git a/apps/desktop/src/setup.ts b/apps/desktop/src/setup.tsdeleted file mode 100644index 60b3fdcd..00000000--- a/apps/desktop/src/setup.ts+++ /dev/null@@ -1,126 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { app } from "electron";-import { existsSync, rmSync, writeFileSync } from "node:fs";-import { join } from "node:path";--import { installCli, isCliInstalled, isCliLinked, uninstallCli } from "./cli-install";-import { healMcpRegistrations, mcpRegistered, registerMcp, registeredAgents, unregisterMcp } from "./mcp-install";-import { pruneLegacySkills } from "./skills-cleanup";--import type { CliMode, CliSetupResult, SetupResult, SetupStatus } from "./main-channels";-import type { CliUninstallResult } from "./cli-install";-import type { McpUnregisterResult } from "./mcp-install";-import { refreshAppMenu } from "./menu";--// 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(mode: CliMode = "auto"): Promise<SetupResult> {- const skills = pruneLegacySkills();- healMcpRegistrations();-- const mcp = registerMcp();- const cli = await ensureCli(mode);-- refreshAppMenu();- return { mcp, cli, skills };-}--/** What `disconnectSetup` did to each half of what `ensureSetup` put in place. */-export type DisconnectResult = { mcp: McpUnregisterResult; cli: CliUninstallResult };--/**- * Whether there is anything for `disconnectSetup` to undo: an agent config- * pointing at the app, or the `dapi` link on PATH.- */-export function setupConnected(): boolean {- return registeredAgents().length > 0 || isCliLinked();-}--/**- * The inverse of `ensureSetup`: takes the app out of every agent config and- * the `dapi` link off PATH. The configs go first because they never prompt;- * the link comes second because it does, and a dismissed prompt should not- * leave the agents half-disconnected. A removed link is remembered as a- * refusal, so the next handoff does not immediately ask to put it back —- * only "Connect Agents…" does.- */-export async function disconnectSetup(): Promise<DisconnectResult> {- const mcp = unregisterMcp();- const cli = await uninstallCli();- if (cli.status === "removed") rememberDecline(true);-- refreshAppMenu();- return { mcp, cli };-}--/**- * The launch pass. It repairs entries this app already owns.- */-export function verifySetup(): SetupStatus {- pruneLegacySkills();- healMcpRegistrations();- return setupStatus();-}--/** What the CLI half of setup would find, without asking for a password. */-function cliStatus(): SetupStatus["cli"] {- if (isCliInstalled()) return "present";- if (!app.isPackaged) return "unavailable";- return existsSync(declinedPath()) ? "declined" : "missing";-}--/**- * Whether the agent configs already point at this build, and where the `dapi`- * symlink stands.- */-export function setupStatus(): SetupStatus {- return { mcp: mcpRegistered(), cli: cliStatus() };-}diff --git a/apps/desktop/src/skills-cleanup.ts b/apps/desktop/src/skills-cleanup.tsindex 36918f4d..3ad56bd4 100644--- a/apps/desktop/src/skills-cleanup.ts+++ b/apps/desktop/src/skills-cleanup.ts@@ -17,18 +17,18 @@ 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"];+/** Home-relative folders of the agents older builds installed skills for. */+const AGENT_DIRS = [".claude", ".codex", ".cursor", ".gemini", ".codeium/windsurf"];+/**- * 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.+ * Where an agent keeps its global skills: `skills/` inside its folder —+ * `~/.claude/skills`, `~/.codex/skills`, and so on.*/const skillsDirs = (): string[] =>- AGENT_TARGETS.map((target) => join(homedir(), target.marker, "skills"));+ AGENT_DIRS.map((dir) => join(homedir(), dir, "skills"));/** The link's target, or null when `path` is missing or not a symlink. */function linkTarget(path: string): string | null {diff --git a/apps/web/src/lib/agents.ts b/apps/web/src/lib/agents.tsindex 9a043ee3..9825e3ad 100644--- a/apps/web/src/lib/agents.ts+++ b/apps/web/src/lib/agents.ts@@ -5,9 +5,6 @@// The coding agents the dashboard offers. Nothing is detected: the list, and// which of them counts as installed, is fixed here.-import { MAIN_CHANNELS } from "@desktop/main-channels";-import { mainBridge } from "@/lib/ipc";-/** A coding agent the home view's picker offers. */export type AgentInfo = {/** Stable id — what the picker remembers the user's choice as. */@@ -32,22 +29,3 @@ const AGENT_ICONS: Record<string, string> = {/** The icon name for `id`, falling back to a generic mark. */export const agentIcon = (id: string | undefined): string =>(id && AGENT_ICONS[id]) || "fx";--/**- * 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 ensureAgentSetup(): Promise<void> {- if (!window.desktop) return;-- const { mcp } = await mainBridge.call(MAIN_CHANNELS.SETUP_ENSURE, {});- if (mcp.status === "error") throw new Error(mcp.error);-}