The VS Code of video editing, built for agents.
TypeScript
Enhance MCP configuration management and menu functionality
konstantin-paulus9d36f71dece1
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex a230818f..44c4f7eb 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -14,7 +14,7 @@ import { enableHeadless, isHeadless } from "./headless";import { agentLaunchUrl, listAgents } from "./agent-detect";import { ensureSetup, setupStatus, verifySetup } from "./setup";import { trackInstall } from "./analytics";-import { setupAppMenu } from "./menu";+import { refreshAppMenu, setupAppMenu } from "./menu";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";import {@@ -292,7 +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.SETUP_ENSURE, ({ cli }) => ensureSetup({ cli }));+ 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),@@ -394,6 +394,7 @@ if (app.requestSingleInstanceLock()) {dapi.start();verifySetup();+ refreshAppMenu();trackInstall();createWindow(!isHiddenLaunch(process.argv));});diff --git a/apps/desktop/src/mcp-config.test.ts b/apps/desktop/src/mcp-config.test.tsindex a294410c..66132e8a 100644--- a/apps/desktop/src/mcp-config.test.ts+++ b/apps/desktop/src/mcp-config.test.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { describe, expect, it } from "vitest";-import { AGENT_TARGETS, readServer, upsertServer } from "./mcp-config";+import { AGENT_TARGETS, readServer, removeServer, upsertServer } from "./mcp-config";const spec = {url: "http://127.0.0.1:3274/mcp",@@ -75,6 +75,24 @@ describe("json configs", () => {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)", () => {@@ -107,5 +125,21 @@ describe("toml configs (codex)", () => {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.tsindex fab14673..c49c10aa 100644--- a/apps/desktop/src/mcp-config.ts+++ b/apps/desktop/src/mcp-config.ts@@ -71,6 +71,16 @@ export function upsertServer(text: string | null, format: AgentTarget["format"],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 };@@ -107,6 +117,13 @@ function upsertJson(text: string | null, entry: ServerEntry): string {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 {@@ -145,6 +162,13 @@ function upsertToml(text: string | null, entry: ServerEntry): string {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;diff --git a/apps/desktop/src/mcp-install.ts b/apps/desktop/src/mcp-install.tsindex dfcdfa37..0980f604 100644--- a/apps/desktop/src/mcp-install.ts+++ b/apps/desktop/src/mcp-install.ts@@ -12,11 +12,14 @@ 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, upsertServer } from "./mcp-config";+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";@@ -115,6 +118,41 @@ export function registerMcp(): McpRegisterResult {};}+/**+ * 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 andiff --git a/apps/desktop/src/menu.ts b/apps/desktop/src/menu.tsindex 32a52d4b..088c0718 100644--- a/apps/desktop/src/menu.ts+++ b/apps/desktop/src/menu.ts@@ -6,6 +6,7 @@ import { app, dialog, Menu } from "electron";import type { MenuItemConstructorOptions } from "electron";import { CLI_LINK_PATH } from "./cli-install";+import { registeredAgents, unregisterMcp } from "./mcp-install";import { ensureSetup } from "./setup";import type { CliSetupResult } from "./main-channels";@@ -30,7 +31,7 @@ function cliDetail(result: CliSetupResult): string | null {// 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" });+ const { mcp, cli, skills } = await ensureSetup("force");if (mcp.status === "error") {await dialog.showMessageBox({@@ -53,6 +54,65 @@ async function connectAgentsFromMenu() {message: "Your agents are connected.",detail: detail.join("\n\n"),});+ refreshAppMenu();+}++// The inverse of the item above: takes the app's MCP entry back out of every+// agent config that has one. 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();+ if (agents.length === 0) {+ refreshAppMenu();+ return;+ }++ const { response } = await dialog.showMessageBox({+ type: "question",+ message: "Disconnect your agents?",+ detail: [+ `Diffusion Studio will be removed from the MCP configuration of ${agents.join(", ")}. Restart the agent to pick it up.`,+ "The dapi command line tool stays installed. Sending a prompt to an agent from the dashboard connects it again.",+ ].join("\n\n"),+ buttons: ["Disconnect", "Cancel"],+ defaultId: 0,+ cancelId: 1,+ });+ if (response !== 0) return;++ const result = unregisterMcp();+ refreshAppMenu();++ if (result.agents.length === 0) {+ await dialog.showMessageBox({+ type: "error",+ message: "Could not disconnect your agents.",+ detail: result.failures.join("\n"),+ });+ return;+ }++ await dialog.showMessageBox({+ type: result.failures.length > 0 ? "warning" : "info",+ message: "Your agents are disconnected.",+ detail: [+ `Disconnected: ${result.agents.join(", ")}. Restart the agent to pick it up.`,+ result.failures.length > 0 ? `Could not update:\n${result.failures.join("\n")}` : null,+ ].filter((line): line is string => line !== null).join("\n\n"),+ });+}++const DISCONNECT_ITEM_ID = "disconnect-agents";++/**+ * Re-reads the agent configs and shows or hides "Disconnect Agents…" to+ * match. Called after anything that writes those configs — 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 = registeredAgents().length > 0;}export function setupAppMenu() {@@ -68,6 +128,12 @@ export function setupAppMenu() {label: "Connect Agents…",click: connectAgentsFromMenu,},+ {+ id: DISCONNECT_ITEM_ID,+ label: "Disconnect Agents…",+ visible: registeredAgents().length > 0,+ click: disconnectAgentsFromMenu,+ },{ type: "separator" },{ role: "services" },{ type: "separator" },diff --git a/apps/desktop/src/setup.ts b/apps/desktop/src/setup.tsindex 4063fb93..27ad2b60 100644--- a/apps/desktop/src/setup.ts+++ b/apps/desktop/src/setup.ts@@ -11,6 +11,7 @@ import { healMcpRegistrations, mcpRegistered, registerMcp } from "./mcp-install"import { pruneLegacySkills } from "./skills-cleanup";import type { CliMode, CliSetupResult, SetupResult, SetupStatus } from "./main-channels";+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@@ -59,11 +60,15 @@ async function ensureCli(mode: CliMode): Promise<CliSetupResult> {* 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> {+export async function ensureSetup(mode: CliMode = "auto"): Promise<SetupResult> {const skills = pruneLegacySkills();healMcpRegistrations();+const mcp = registerMcp();- return { mcp, cli: await ensureCli(cli), skills };+ const cli = await ensureCli(mode);++ refreshAppMenu();+ return { mcp, cli, skills };}/**