The VS Code of video editing, built for agents.
TypeScript
Implement Windows CLI shim and update installation process
konstantin-paulus307a6a4a7603
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 23454bbc..c92546a8 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -10,7 +10,9 @@"build": "esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.js && node -e \"process.platform !== 'win32' && require('node:fs').chmodSync('dist/index.js', 0o755)\"","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"+ "symlink:create": "npm run build && ln -sf \"$PWD/dist/index.js\" /opt/homebrew/bin/dapi",+ "shim:create": "npm run build && node scripts/dev-shim.mjs",+ "shim:remove": "node scripts/dev-shim.mjs --remove"},"dependencies": {"@diffusionstudio/dapi": "*",diff --git a/apps/cli/scripts/dev-shim.mjs b/apps/cli/scripts/dev-shim.mjsnew file mode 100644index 00000000..abd1c234--- /dev/null+++ b/apps/cli/scripts/dev-shim.mjs@@ -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/. */++// Windows counterpart of `symlink:create`: points the `dapi` shim at this+// workspace's build, run on the system's Node. It goes where the packaged app+// keeps its own shim (apps/desktop/src/cli-windows.ts), which is also where a+// dev build of the app looks for the binary it registers with agents. The two+// share the file: a packaged app rewrites it on launch, so run this again+// after using one.+//+// node scripts/dev-shim.mjs write the shim+// node scripts/dev-shim.mjs --remove delete it++import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, win32 } from "node:path";+import { fileURLToPath } from "node:url";++if (process.platform !== "win32") {+ console.error("dev-shim is for Windows; use `npm run symlink:create` on macOS.");+ process.exit(1);+}++const local = process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local");+const dir = join(local, "DiffusionStudio", "bin");+const shim = join(dir, "dapi.cmd");++if (process.argv.includes("--remove")) {+ rmSync(shim, { force: true });+ console.log(`dev-shim: removed ${shim}`);+ process.exit(0);+}++const script = join(dirname(fileURLToPath(import.meta.url)), "..", "dist", "index.js");+const batch = (path) => path.replaceAll("%", "%%");++mkdirSync(dir, { recursive: true });+writeFileSync(shim, ["@echo off", "setlocal", `node "${batch(script)}" %*`, ""].join("\r\n"));+console.log(`dev-shim: ${shim} -> ${script}`);++const onPath = (process.env.PATH ?? "")+ .split(";")+ .some((entry) => win32.normalize(entry).replace(/\\+$/, "").toLowerCase() === dir.toLowerCase());+if (!onPath) console.log(`dev-shim: add ${dir} to your PATH to run \`dapi\` from a terminal.`);diff --git a/apps/cli/src/cli-client.ts b/apps/cli/src/cli-client.tsindex bd576f7f..92dad66d 100644--- a/apps/cli/src/cli-client.ts+++ b/apps/cli/src/cli-client.ts@@ -2,7 +2,7 @@* 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 { execFile } from "node:child_process";+import { execFile, spawn } from "node:child_process";import { Client } from "@modelcontextprotocol/sdk/client/index.js";import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";import { MCP_URL } from "@diffusionstudio/dapi";@@ -42,7 +42,7 @@ export async function call<N extends ToolName>(name: N, input: ToolInput<N>): Pr}return result.structuredContent as ToolOutput<N>;} finally {- await client.close().catch(() => {});+ await client.close().catch(() => { });}}@@ -52,7 +52,7 @@ export async function ping(): Promise<void> {try {await client.ping();} finally {- await client.close().catch(() => {});+ await client.close().catch(() => { });}}@@ -77,22 +77,40 @@ export function isAppDown(e: unknown): boolean {return false;}-/**- * Launches the app, or surfaces the running instance: `open -a` on a running- * app only activates it, so this is safe to always run. macOS only; elsewhere- * it resolves false and the caller falls through to the connection.- *- * The bundled `dapi` runs as Electron with ELECTRON_RUN_AS_NODE=1, and `open`- * hands its environment to the app it launches — left in, the app boots as- * plain Node and never answers.- */-export function launchApp(background: boolean): Promise<boolean> {- if (process.platform !== "darwin") return Promise.resolve(false);++function launchWin32(background: boolean): Promise<boolean> {+ if (!process.versions.electron) return Promise.resolve(false);+ const { ELECTRON_RUN_AS_NODE: _, ...env } = process.env;+ return new Promise((res) => {+ const child = spawn(process.execPath, background ? ["--hidden"] : [], {+ detached: true,+ stdio: "ignore",+ env,+ });+ child.once("error", () => res(false));+ child.once("spawn", () => {+ child.unref();+ res(true);+ });+ });+}++function launchDarwin(background: boolean): Promise<boolean> {const args = background ? ["-g", "-a", APP_NAME, "--args", "--hidden"] : ["-a", APP_NAME];const { ELECTRON_RUN_AS_NODE: _, ...env } = process.env;return new Promise((res) => execFile("open", args, { env }, (err) => res(!err)));}+/**+ * Launches the app, or surfaces the running instance+ */+export function launchApp(background: boolean): Promise<boolean> {+ if (process.platform === "win32") return launchWin32(background);+ if (process.platform === "darwin") return launchDarwin(background);++ return Promise.resolve(false);+}+/*** Bridges the cold-start gap after launching the app: retries while the app* looks down, until it answers a ping.diff --git a/apps/desktop/WINDOWS.md b/apps/desktop/WINDOWS.mdindex 73ee170c..36fd4ecb 100644--- a/apps/desktop/WINDOWS.md+++ b/apps/desktop/WINDOWS.md@@ -130,6 +130,17 @@ Acceptance:Goal: the window looks and behaves like a first-class Windows app.+Status: implemented on macOS, not yet run on Windows. Differences from the+tasks as written:+- The app has a light/dark switch, so the overlay cannot be one fixed colour.+ The renderer reports the color mode over `WINDOW_SET_COLOR_MODE`+ (`use-title-bar-color-mode.ts`) and main calls `setTitleBarOverlay`.+- The clearance is one CSS variable, `--titlebar-controls-width` in+ `index.css`, built from the `titlebar-area` env variables; it is 0 wherever+ there is no overlay. Only the inspector header sits under the controls and+ uses it. The chat header moved into the left sidebar since this plan was+ written and needs nothing.+Tasks:1. **BrowserWindow options** (`apps/desktop/src/main.ts`, `createWindow`):@@ -168,6 +179,22 @@ Acceptance:Goal: after clicking "Install CLI" in settings, `dapi` works in a freshterminal and keeps working after the app updates.+Status: implemented on macOS (`cli-windows.ts`, unit-tested), not yet run on+Windows. Differences from the tasks as written:+- The shim holds the absolute path of the current executable, rewritten on+ every packaged launch and from the install/update hooks. Whether Squirrel's+ stub exe forwards stdio is still to be checked on hardware; if it does, the+ shim can point at the stub instead.+- PATH is edited through the registry from PowerShell, not+ `[Environment]::SetEnvironmentVariable`, which would expand every+ `%VARIABLE%` already in the user's PATH and store it as a plain string.+ Deleting a variable that does not exist afterwards makes .NET send the+ settings-change broadcast.+- `uninstallCli` only takes the folder off PATH. The shim stays, because MCP+ registrations run it; the Squirrel uninstall hook removes it.+- The settings card no longer mentions `/usr/local/bin`; only the "installed"+ toast differs on Windows (it says to open a new terminal).+Tasks:1. **Staged wrapper** (`apps/desktop/scripts/stage-cli.mjs`): on win32 emit@@ -225,6 +252,11 @@ Acceptance:Goal: every agent in the settings list connects on Windows.+Status: implemented on macOS (unit-tested), not yet run on Windows. Agent+paths are `{ root: "home" | "appData", path }`, and `appData` resolves through+Electron's `app.getPath("appData")`, so the target table has no platform+branches. The Squirrel uninstall hook removes our entry from every agent.+Tasks:1. **Per-platform targets** (`apps/desktop/src/mcp-config.ts`): make@@ -258,6 +290,17 @@ Acceptance:Goal: no dapi tool answers "macOS only".+Status: implemented on macOS, not yet run on Windows. `queryLocalFonts` was+probed in Electron on macOS: it needs no user gesture, but Chromium rejects it+("Page needs to be visible") once a window has been shown and then hidden or+minimized. A never-shown window counts as visible, so `--hidden` launches were+never affected. The main window therefore sets `backgroundThrottling: false`,+which keeps the page visible in every state; confirm the same on Windows.+Still to do on macOS: one `dapi fonts` call against a dev build, since+the tool changed process. Google Drive's streaming drive is recognised by+shape (a drive root holding `My Drive` on a machine with DriveFS), because its+letter is only in the client's database; check that on hardware.+Tasks:1. **`fonts`**: move the handler from `apps/desktop/src/dapi/handlers/fonts.ts`@@ -333,6 +376,10 @@ Acceptance:Goal: developing on a Windows machine is as easy as on macOS, and the appgets the Windows 11 look.+Status: tasks 1 and 2 implemented on macOS, not yet run on Windows+(`scripts/dev-desktop.mjs`, `npm run shim:create` in `apps/cli`). Tasks 3 to 5+are open.+Tasks:1. **`scripts/dev-desktop.mjs`**: port reclaim uses `lsof` and `ps`; treediff --git a/apps/desktop/scripts/stage-cli.mjs b/apps/desktop/scripts/stage-cli.mjsindex 82d53811..5294edbf 100644--- a/apps/desktop/scripts/stage-cli.mjs+++ b/apps/desktop/scripts/stage-cli.mjs@@ -5,9 +5,16 @@// 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 Claude Desktop runs as `dapi mcp`-// (registered by mcp-install.ts) and the file that gets-// linked into PATH+// cli/bin/dapi macOS shell wrapper: what Claude Desktop runs as+// `dapi mcp` (registered by mcp-install.ts) and the file+// that gets linked into PATH+// cli/bin/dapi.cmd Windows wrapper, relative to the install folder. PATH+// and the agents get a shim outside the install folder+// instead (src/cli-windows.ts), since Squirrel moves the+// app on every update; this one is for running the CLI+// straight out of an install.+// Each host stages its own wrapper; `--all` stages both, so a macOS host can+// produce a Windows tree for inspection.import { chmodSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";@@ -25,6 +32,8 @@ 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.+const all = process.argv.includes("--all");+const wrapper = `#!/bin/shSELF="$0"while [ -L "$SELF" ]; do@@ -38,7 +47,23 @@ DIR="$(cd "$(dirname "$SELF")" && pwd)"export DIFFUSION_APP_PATH="$(cd "$DIR/../../../.." && pwd)"ELECTRON_RUN_AS_NODE=1 exec "$DIR/../../../MacOS/Diffusion Studio" "$DIR/../dapi.js" "$@"`;-writeFileSync(join(stageDir, "bin", "dapi"), wrapper);-chmodSync(join(stageDir, "bin", "dapi"), 0o755);++if (all || process.platform !== "win32") {+ writeFileSync(join(stageDir, "bin", "dapi"), wrapper);+ chmodSync(join(stageDir, "bin", "dapi"), 0o755);+}++// Staged at <install>\resources\cli\bin, three folders below the executable.+const cmdWrapper = [+ "@echo off",+ "setlocal",+ 'set "ELECTRON_RUN_AS_NODE=1"',+ '"%~dp0..\\..\\..\\Diffusion Studio.exe" "%~dp0..\\dapi.js" %*',+ "",+].join("\r\n");++if (all || process.platform === "win32") {+ writeFileSync(join(stageDir, "bin", "dapi.cmd"), cmdWrapper);+}console.log(`stage-cli: staged dapi at ${stageDir}`);diff --git a/apps/desktop/src/cli-install.ts b/apps/desktop/src/cli-install.tsindex 955ccd6a..d2d5ddc6 100644--- a/apps/desktop/src/cli-install.ts+++ b/apps/desktop/src/cli-install.ts@@ -2,15 +2,12 @@* 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/. */-// The `dapi` command on PATH: a symlink from /usr/local/bin to the wrapper-// the app ships in its resources. Creating it needs an admin password,-// which macOS asks for through osascript so the app itself never sees-// credentials; removing a link asks only when the folder demands it.import { app } from "electron";import { execFile } from "node:child_process";import { existsSync, lstatSync, unlinkSync } from "node:fs";import { join } from "node:path";+import { addShimToPath, removeShimFromPath, shimOnPath, shimPath, writeShim } from "./cli-windows";import type { CliInstallResult, CliStatus, CliUninstallResult } from "./main-channels";@@ -37,13 +34,40 @@ function installedPath(): string | null {return null;}-/** Where `dapi` stands on this machine, without asking for a password. */-export function cliStatus(): CliStatus {+/**+ * Rewrites the Windows shim so it names this executable. Runs on every+ * packaged launch, because an update moved the app to a new folder; the+ * agents' MCP entries point at the shim whether or not it is on PATH.+ */+export function refreshCliShim(): void {+ if (process.platform !== "win32" || !app.isPackaged) return;+ writeShim().catch((e) => console.error("cli shim: could not write", e));+}++async function cliStatusWin32(): Promise<CliStatus> {+ const installed = await shimOnPath().catch(() => false);+ if (installed) {+ return { installed: true, path: shimPath(), managed: true, available: true };+ }+ return { installed: false, path: null, managed: false, available: app.isPackaged };+}++async function cliStatusDarwin(): Promise<CliStatus> {const path = installedPath();- if (path) return { installed: true, path, managed: isLink(path), available: true };+ if (path) {+ return { installed: true, path, managed: isLink(path), available: true };+ }return { installed: false, path: null, managed: false, available: app.isPackaged };}+/** Where `dapi` stands on this machine, without asking for a password. */+export async function cliStatus(): Promise<CliStatus> {+ if (process.platform === "win32") return cliStatusWin32();+ if (process.platform === "darwin") return cliStatusDarwin();++ return { installed: false, path: null, managed: false, available: false };+}+// The standard macOS admin prompt, for the one shell line that needs it.function elevated(shell: string): Promise<void> {const script = `do shell script "${shell.replaceAll('"', '\\"')}" with administrator privileges`;@@ -55,29 +79,53 @@ function elevated(shell: string): Promise<void> {/** osascript error -128: the user dismissed the prompt. Not an error, not done. */const cancelled = (e: unknown): boolean => ((e as Error).message ?? "").includes("-128");+async function installCliDarwin(): Promise<CliInstallResult> {+ const wrapper = join(process.resourcesPath, "cli", "bin", "dapi");+ try {+ await elevated(`mkdir -p /usr/local/bin && ln -sf '${wrapper}' '${CLI_LINK_PATH}'`);+ return { status: "installed" };+ } catch (e) {+ return cancelled(e) ? { status: "cancelled" } : { status: "error", error: (e as Error).message };+ }+}++async function installCliWin32(): Promise<CliInstallResult> {+ try {+ await writeShim();+ await addShimToPath();+ return { status: "installed" };+ } catch (e) {+ return { status: "error", error: (e as Error).message };+ }+}+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.",+ error: `Installing the CLI is only available in the packaged app. Use \`npm run ${process.platform === "win32" ? "shim:create" : "symlink:create"}\` in development.`,};}- const wrapper = join(process.resourcesPath, "cli", "bin", "dapi");+ if (process.platform === "win32") return installCliWin32();+ if (process.platform === "darwin") return installCliDarwin();++ return {+ status: "error",+ error: `Installing the CLI is only available on Windows and macOS.`,+ };+}++async function uninstallCliWin32(): Promise<CliUninstallResult> {try {- await elevated(`mkdir -p /usr/local/bin && ln -sf '${wrapper}' '${CLI_LINK_PATH}'`);- return { status: "installed" };+ if (!(await shimOnPath())) return { status: "absent" };+ await removeShimFromPath();+ return { status: "removed" };} catch (e) {- return cancelled(e) ? { status: "cancelled" } : { status: "error", error: (e as Error).message };+ return { status: "error", error: (e as Error).message };}}-/**- * Takes the `dapi` link off PATH, whichever of the two locations holds it.- * Only a symlink is touched: a real binary somebody put there is not ours- * to delete. The plain unlink covers Homebrew's user-owned bin; when the- * folder refuses (/usr/local/bin is root's), the admin prompt takes over.- */-export async function uninstallCli(): Promise<CliUninstallResult> {+async function uninstallCliDarwin(): Promise<CliUninstallResult> {const path = installedPath();if (!path) return { status: "absent" };if (!isLink(path)) {@@ -97,3 +145,17 @@ export async function uninstallCli(): Promise<CliUninstallResult> {return cancelled(e) ? { status: "cancelled" } : { status: "error", error: (e as Error).message };}}+++/**+ * Takes the `dapi` link off PATH, whichever of the two locations holds it.+ */+export async function uninstallCli(): Promise<CliUninstallResult> {+ if (process.platform === "win32") return uninstallCliWin32();+ if (process.platform === "darwin") return uninstallCliDarwin();++ return {+ status: "error",+ error: `Uninstalling the CLI is only available on Windows and macOS.`,+ };+}diff --git a/apps/desktop/src/cli-windows.test.ts b/apps/desktop/src/cli-windows.test.tsnew file mode 100644index 00000000..b34dab69--- /dev/null+++ b/apps/desktop/src/cli-windows.test.ts@@ -0,0 +1,57 @@+/* 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/. */++// The parts of the Windows CLI install that are decisions rather than system+// calls: where the shim lives, what it says, and how the user's PATH is+// edited without disturbing the entries around ours.++import { describe, expect, it } from "vitest";++import { pathHas, pathWith, pathWithout, shimContent, shimDir, shimPath, stagedScript } from "./cli-windows";++const local = "C:\\Users\\me\\AppData\\Local";+const exe = `${local}\\DiffusionStudio\\app-1.2.0\\Diffusion Studio.exe`;+const dir = `${local}\\DiffusionStudio\\bin`;++describe("shim", () => {+ it("lives outside the versioned app folder", () => {+ expect(shimDir({ LOCALAPPDATA: local })).toBe(dir);+ expect(shimPath({ LOCALAPPDATA: local })).toBe(`${dir}\\dapi.cmd`);+ });++ it("runs the staged CLI on the app's executable in Node mode", () => {+ expect(stagedScript(exe)).toBe(`${local}\\DiffusionStudio\\app-1.2.0\\resources\\cli\\dapi.js`);+ expect(shimContent(exe).split("\r\n")).toEqual([+ "@echo off",+ "setlocal",+ 'set "ELECTRON_RUN_AS_NODE=1"',+ `"${exe}" "${stagedScript(exe)}" %*`,+ "",+ ]);+ });++ it("escapes percent signs, which batch files would expand", () => {+ expect(shimContent("C:\\Users\\100%me\\app.exe", "C:\\x\\dapi.js")).toContain('"C:\\Users\\100%%me\\app.exe"');+ });+});++describe("user PATH", () => {+ const path = "%USERPROFILE%\\.cargo\\bin;C:\\Tools";++ it("appends the folder once, leaving other entries as written", () => {+ expect(pathWith(path, dir)).toBe(`${path};${dir}`);+ expect(pathWith(`${path};${dir}`, dir)).toBe(`${path};${dir}`);+ expect(pathWith("", dir)).toBe(dir);+ });++ it("matches without case and trailing separators", () => {+ expect(pathHas(`${path};${dir.toUpperCase()}\\`, dir)).toBe(true);+ expect(pathHas(path, dir)).toBe(false);+ });++ it("removes every spelling of the folder and nothing else", () => {+ expect(pathWithout(`${dir}\;${path};${dir.toLowerCase()}`, dir)).toBe(path);+ expect(pathWithout(path, dir)).toBe(path);+ });+});diff --git a/apps/desktop/src/cli-windows.ts b/apps/desktop/src/cli-windows.tsnew file mode 100644index 00000000..156e2000--- /dev/null+++ b/apps/desktop/src/cli-windows.ts@@ -0,0 +1,141 @@+/* 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/. */++// The `dapi` command on Windows. Squirrel installs every version into its own+// `app-<version>` folder, so nothing durable may point at the wrapper the app+// ships in its resources. What goes on PATH (and into the agents' MCP+// configs) is a shim in a folder that never moves:+// %LOCALAPPDATA%\DiffusionStudio\bin\dapi.cmd+// The app rewrites it on every packaged launch and from Squirrel's update+// hook, so it always names the current executable. Installing the CLI is then+// only a matter of putting that folder on the user's PATH, which needs no+// administrator.+//+// Nothing here imports electron, so the Squirrel hooks can use it before the+// app is ready and the tests can run it anywhere.++import { execFile } from "node:child_process";+import { mkdir, rm } from "node:fs/promises";+import { homedir } from "node:os";+import { win32 } from "node:path";++import { writeFileAtomic } from "./atomic";++/** The folder that holds the shim: the one entry we add to PATH. */+export function shimDir(env: NodeJS.ProcessEnv = process.env): string {+ const local = env.LOCALAPPDATA || win32.join(homedir(), "AppData", "Local");+ return win32.join(local, "DiffusionStudio", "bin");+}++export function shimPath(env: NodeJS.ProcessEnv = process.env): string {+ return win32.join(shimDir(env), "dapi.cmd");+}++/** `dapi.js` as the packaged app stages it, next to `execPath`'s resources. */+export function stagedScript(execPath: string): string {+ return win32.join(win32.dirname(execPath), "resources", "cli", "dapi.js");+}++// A literal `%` would start a variable expansion inside a batch file.+const batch = (path: string): string => path.replaceAll("%", "%%");++/**+ * The shim's text: the CLI bundle on the app's own Electron binary in Node+ * mode, like the macOS wrapper, but with both paths spelled out because the+ * shim does not live beside them.+ */+export function shimContent(execPath: string, script: string = stagedScript(execPath)): string {+ return [+ "@echo off",+ "setlocal",+ 'set "ELECTRON_RUN_AS_NODE=1"',+ `"${batch(execPath)}" "${batch(script)}" %*`,+ "",+ ].join("\r\n");+}++/** Points the shim at `execPath`. Safe to repeat; the write lands whole. */+export async function writeShim(execPath: string = process.execPath, script?: string): Promise<void> {+ await mkdir(shimDir(), { recursive: true });+ await writeFileAtomic(shimPath(), shimContent(execPath, script));+}++export async function removeShim(): Promise<void> {+ await rm(shimDir(), { recursive: true, force: true });+}++// PATH entries compare without case and without a trailing separator.+const normalize = (entry: string): string => entry.trim().replace(/[\\/]+$/, "").toLowerCase();++const entries = (path: string): string[] => path.split(";").filter((entry) => entry.trim() !== "");++export function pathHas(path: string, dir: string): boolean {+ return entries(path).some((entry) => normalize(entry) === normalize(dir));+}++/** `path` with `dir` appended, or unchanged when it is already there. */+export function pathWith(path: string, dir: string): string {+ return pathHas(path, dir) ? path : [...entries(path), dir].join(";");+}++/** `path` without any spelling of `dir`. */+export function pathWithout(path: string, dir: string): string {+ return entries(path)+ .filter((entry) => normalize(entry) !== normalize(dir))+ .join(";");+}++// The user PATH lives in HKCU\Environment. It is read and written through the+// registry rather than [Environment]::Get/SetEnvironmentVariable, which would+// expand every %VARIABLE% in the entries that are already there and store the+// result as a plain string. `setx` is out too: it truncates at 1024+// characters. Removing a variable that does not exist is the cheap way to+// make .NET broadcast WM_SETTINGCHANGE, so new terminals see the change.+// The value travels through the environment so nothing needs quoting.+const READ_PATH = `+$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')+[Console]::Out.Write($key.GetValue('Path', '', 'DoNotExpandEnvironmentNames'))+`;++const WRITE_PATH = `+$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)+$kind = if ($key.GetValueNames() -contains 'Path') { $key.GetValueKind('Path') } else { 'ExpandString' }+$value = if ($env:DAPI_USER_PATH) { $env:DAPI_USER_PATH } else { '' }+$key.SetValue('Path', $value, $kind)+[Environment]::SetEnvironmentVariable('DAPI_PATH_BROADCAST', $null, 'User')+`;++function powershell(script: string, env: NodeJS.ProcessEnv = {}): Promise<string> {+ return new Promise((resolve, reject) => {+ execFile(+ "powershell.exe",+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],+ { env: { ...process.env, ...env }, windowsHide: true },+ (err, stdout) => (err ? reject(err) : resolve(stdout)),+ );+ });+}++export const readUserPath = (): Promise<string> => powershell(READ_PATH);++export async function writeUserPath(path: string): Promise<void> {+ await powershell(WRITE_PATH, { DAPI_USER_PATH: path });+}++/** Whether the shim folder is on the user's PATH. */+export async function shimOnPath(): Promise<boolean> {+ return pathHas(await readUserPath(), shimDir());+}++export async function addShimToPath(): Promise<void> {+ const path = await readUserPath();+ const next = pathWith(path, shimDir());+ if (next !== path) await writeUserPath(next);+}++export async function removeShimFromPath(): Promise<void> {+ const path = await readUserPath();+ const next = pathWithout(path, shimDir());+ if (next !== path) await writeUserPath(next);+}diff --git a/apps/desktop/src/cloud-sync-windows.test.ts b/apps/desktop/src/cloud-sync-windows.test.tsnew file mode 100644index 00000000..1350f0b1--- /dev/null+++ b/apps/desktop/src/cloud-sync-windows.test.ts@@ -0,0 +1,49 @@+/* 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 { dropboxRoots, isUnder, windowsCloudSyncKind } from "./cloud-sync-windows";++const home = "C:\\Users\\me";++describe("isUnder", () => {+ it("compares the way Windows does: no case, whole segments", () => {+ expect(isUnder("c:\\users\\ME\\OneDrive\\Videos\\clip", "C:\\Users\\me\\OneDrive")).toBe(true);+ expect(isUnder("C:\\Users\\me\\OneDrive", "C:\\Users\\me\\OneDrive\\")).toBe(true);+ expect(isUnder("C:\\Users\\me\\OneDrive-old\\clip", "C:\\Users\\me\\OneDrive")).toBe(false);+ });+});++describe("dropboxRoots", () => {+ it("reads every linked account's folder", () => {+ const info = JSON.stringify({+ personal: { path: "D:\\Dropbox", host: 1 },+ business: { path: "D:\\Dropbox (Acme)", host: 2 },+ });+ expect(dropboxRoots(info)).toEqual(["D:\\Dropbox", "D:\\Dropbox (Acme)"]);+ });++ it("finds nothing in a file it cannot read", () => {+ expect(dropboxRoots("{ not json")).toEqual([]);+ expect(dropboxRoots("null")).toEqual([]);+ expect(dropboxRoots('{"personal":{}}')).toEqual([]);+ });+});++describe("windowsCloudSyncKind", () => {+ // No LOCALAPPDATA: nothing is read from disk, only the fixed locations apply.+ const env = { OneDrive: "C:\\Users\\me\\OneDrive" };++ it("names the service a folder sits under", async () => {+ expect(await windowsCloudSyncKind("C:\\Users\\me\\OneDrive\\Projects\\a", home, env)).toBe("OneDrive");+ expect(await windowsCloudSyncKind("C:\\Users\\me\\Dropbox\\a", home, env)).toBe("Dropbox");+ expect(await windowsCloudSyncKind("C:\\Users\\me\\iCloudDrive\\a", home, env)).toBe("iCloud Drive");+ });++ it("leaves plain local disk alone", async () => {+ expect(await windowsCloudSyncKind("C:\\Users\\me\\Videos\\a", home, env)).toBeNull();+ expect(await windowsCloudSyncKind("G:\\My Drive\\a", home, env)).toBeNull();+ });+});diff --git a/apps/desktop/src/cloud-sync-windows.ts b/apps/desktop/src/cloud-sync-windows.tsnew file mode 100644index 00000000..10828a80--- /dev/null+++ b/apps/desktop/src/cloud-sync-windows.ts@@ -0,0 +1,89 @@+/* 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/. */++// Where the sync services keep their folders on Windows. macOS marks a synced+// folder with a File Provider attribute that can simply be asked for; Windows+// has nothing like it, so each service is found the way it announces itself:+// OneDrive through its environment variables, Dropbox through the info.json+// it writes for exactly this purpose, Google Drive through the streaming+// drive it mounts, iCloud through its fixed folder.++import { access, readFile } from "node:fs/promises";+import { win32 } from "node:path";++/** A folder a service syncs, and the service's name as the warning spells it. */+export type SyncRoot = [dir: string, label: string];++const exists = (path: string): Promise<boolean> => access(path).then(() => true, () => false);++/** Whether `path` is `root` or inside it, the way Windows compares paths: without case. */+export function isUnder(path: string, root: string): boolean {+ const child = win32.resolve(path).toLowerCase();+ const parent = win32.resolve(root).toLowerCase().replace(/\\+$/, "");+ return child === parent || child.startsWith(parent + "\\");+}++/** The folders named in Dropbox's info.json: one per linked account, personal and business. */+export function dropboxRoots(infoJson: string): string[] {+ try {+ const info: unknown = JSON.parse(infoJson);+ if (typeof info !== "object" || info === null) return [];+ return Object.values(info)+ .map((account) => (account as { path?: unknown } | null)?.path)+ .filter((path): path is string => typeof path === "string" && path !== "");+ } catch {+ return [];+ }+}++/** Every sync root that can be named without looking at the path in question. */+export async function windowsSyncRoots(home: string, env: NodeJS.ProcessEnv = process.env): Promise<SyncRoot[]> {+ const roots: SyncRoot[] = [[win32.join(home, "iCloudDrive"), "iCloud Drive"]];++ for (const key of ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]) {+ const dir = env[key];+ if (dir) roots.push([dir, "OneDrive"]);+ }++ const dropbox: string[] = [];+ for (const base of [env.LOCALAPPDATA, env.APPDATA]) {+ if (!base) continue;+ const text = await readFile(win32.join(base, "Dropbox", "info.json"), "utf8").catch(() => null);+ if (text) dropbox.push(...dropboxRoots(text));+ }+ // No info.json (an old or half-installed client): the default location.+ if (dropbox.length === 0) dropbox.push(win32.join(home, "Dropbox"));+ for (const dir of dropbox) roots.push([dir, "Dropbox"]);++ // Google Drive in mirror mode keeps a real folder, by default in the home.+ if (await driveFsInstalled(env)) {+ roots.push([win32.join(home, "My Drive"), "Google Drive"], [win32.join(home, "Google Drive"), "Google Drive"]);+ }++ return roots;+}++function driveFsInstalled(env: NodeJS.ProcessEnv): Promise<boolean> {+ return env.LOCALAPPDATA ? exists(win32.join(env.LOCALAPPDATA, "Google", "DriveFS")) : Promise.resolve(false);+}++/**+ * Whether `path` is on Google Drive's streaming drive: a drive letter of its+ * own (G: unless the user moved it) whose root holds `My Drive`. The letter is+ * only in the client's database, so the drive is recognised by that shape,+ * and only on a machine that has the client.+ */+export async function onGoogleDriveStream(path: string, env: NodeJS.ProcessEnv = process.env): Promise<boolean> {+ const root = win32.parse(win32.resolve(path)).root;+ if (!/^[a-z]:\\$/i.test(root)) return false;+ return (await driveFsInstalled(env)) && (await exists(win32.join(root, "My Drive")));+}++/** The service syncing `path` on Windows, or null. */+export async function windowsCloudSyncKind(path: string, home: string, env: NodeJS.ProcessEnv = process.env): Promise<string | null> {+ for (const [dir, label] of await windowsSyncRoots(home, env)) {+ if (isUnder(path, dir)) return label;+ }+ return (await onGoogleDriveStream(path, env)) ? "Google Drive" : null;+}diff --git a/apps/desktop/src/dapi/handler.ts b/apps/desktop/src/dapi/handler.tsindex dcc7cc64..f7a32294 100644--- a/apps/desktop/src/dapi/handler.ts+++ b/apps/desktop/src/dapi/handler.ts@@ -15,7 +15,7 @@ export type MainContext = {};/** The tools that need the file system or a child process, not a window. */-export type MainToolName = "logs" | "fonts" | "report";+export type MainToolName = "logs" | "report";export type MainHandler<N extends MainToolName> = (args: ToolArgs<N>, ctx: MainContext) => Promise<ToolResult<N>>;diff --git a/apps/desktop/src/dapi/handlers/fonts.ts b/apps/desktop/src/dapi/handlers/fonts.tsdeleted file mode 100644index 25961210..00000000--- a/apps/desktop/src/dapi/handlers/fonts.ts+++ /dev/null@@ -1,89 +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 { spawnSync } from "node:child_process";-import { platform } from "node:os";-import { DapiError, FONT_LIMIT } from "@diffusionstudio/dapi";--import type { FontFamily } from "@diffusionstudio/dapi";-import type { MainHandler } from "../handler";--// JXA script that walks every registered font family via NSFontManager and-// emits each variant's CSS-style weight, italic flag, and CSS `local()` source.-// Runs via `osascript`.-const LIST_FONTS_JXA = `-ObjC.import("AppKit");--function nsfmWeightToCss(w) {- if (w <= 1) return "100";- if (w <= 2) return "200";- if (w <= 3) return "300";- if (w <= 5) return "400";- if (w <= 6) return "500";- if (w <= 8) return "600";- if (w <= 9) return "700";- if (w <= 11) return "800";- return "900";-}--function run() {- var fm = $.NSFontManager.sharedFontManager;- var families = fm.availableFontFamilies;- var out = [];- for (var i = 0; i < families.count; i++) {- var family = ObjC.unwrap(families.objectAtIndex(i));- if (family.charAt(0) === ".") continue;- var members = fm.availableMembersOfFontFamily(family);- if (!members || members.isNil()) continue;- var variants = [];- for (var j = 0; j < members.count; j++) {- var m = members.objectAtIndex(j);- var fontName = ObjC.unwrap(m.objectAtIndex(0));- var styleName = ObjC.unwrap(m.objectAtIndex(1));- var weight = ObjC.unwrap(m.objectAtIndex(2));- var traits = ObjC.unwrap(m.objectAtIndex(3));- var fullName = styleName === "Regular" ? family : family + " " + styleName;- variants.push({- weight: nsfmWeightToCss(weight),- style: (traits & 1) !== 0 ? "italic" : "normal",- source: "local('" + fullName + "'), local('" + fontName + "')",- });- }- if (variants.length > 0) out.push({ family: family, variants: variants });- }- return JSON.stringify(out);-}-`;--function listLocalFonts(): FontFamily[] {- if (platform() !== "darwin") {- throw new DapiError("unsupported", "fonts is only supported on macOS.");- }- const result = spawnSync("osascript", ["-l", "JavaScript", "-e", LIST_FONTS_JXA], {- encoding: "utf8",- maxBuffer: 16 * 1024 * 1024,- });- if (result.status !== 0) {- throw new Error(result.stderr.trim() || "Failed to enumerate fonts.");- }- return JSON.parse(result.stdout.trim()) as FontFamily[];-}--export const fonts: MainHandler<"fonts"> = async ({ family, weights, style, limit = FONT_LIMIT }) => {- const pattern = family?.toLowerCase();- const wanted = weights && weights.length > 0 ? new Set(weights) : null;-- const families: FontFamily[] = [];- for (const entry of listLocalFonts()) {- if (pattern && !entry.family.toLowerCase().includes(pattern)) continue;- const variants = entry.variants.filter((v) => {- if (wanted && !wanted.has(v.weight)) return false;- if (style && v.style !== style) return false;- return true;- });- if (variants.length === 0) continue;- families.push({ family: entry.family, variants });- }- return { families: families.slice(0, limit), total: families.length };-};diff --git a/apps/desktop/src/dapi/handlers/index.ts b/apps/desktop/src/dapi/handlers/index.tsindex a6987f2e..b34ad023 100644--- a/apps/desktop/src/dapi/handlers/index.ts+++ b/apps/desktop/src/dapi/handlers/index.ts@@ -3,10 +3,9 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { logs } from "./logs";-import { fonts } from "./fonts";import { report } from "./report";import type { MainHandlers } from "../handler";/** Every tool main answers itself, keyed by its catalog name. */-export const mainHandlers: MainHandlers = { logs, fonts, report };+export const mainHandlers: MainHandlers = { logs, report };diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 49be16cc..fd2de15e 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -34,6 +34,7 @@ export const MAIN_CHANNELS = {AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",WINDOW_IS_FULLSCREEN: "window:is-fullscreen",+ WINDOW_SET_COLOR_MODE: "window:set-color-mode",WINDOW_CAPTURE: "window:capture",FILE_TRANSFER: "file:transfer",FILE_WRITE_OPEN: "file:write-open",@@ -189,6 +190,7 @@ export type MainRequestMap = {response: string | null;};[MAIN_CHANNELS.WINDOW_IS_FULLSCREEN]: { request: void; response: boolean };+ [MAIN_CHANNELS.WINDOW_SET_COLOR_MODE]: { request: { mode: "light" | "dark" }; response: void };[MAIN_CHANNELS.WINDOW_CAPTURE]: { request: void; response: ScreenshotResult };[MAIN_CHANNELS.FILE_TRANSFER]: {request: { selector: string; absolutePath: string };diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 24353444..72f07019 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -12,7 +12,7 @@ import { updateElectronApp } from "update-electron-app";import { tempPathFor } from "./atomic";import { DapiServer } from "./dapi/server";import { agentChatEndpoint, deleteProjectChats, startAgentChat, stopAgentChat } from "./agent-chat";-import { cliStatus, installCli, uninstallCli } from "./cli-install";+import { cliStatus, installCli, refreshCliShim, uninstallCli } from "./cli-install";import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";import { enableHeadless } from "./headless";import { trackEvent, trackInstall } from "./analytics";@@ -55,6 +55,13 @@ const DEV_URL = "http://localhost:5173";const AUTH_PROTOCOL = "diffusion";const MACOS_CORNER_RADIUS = 18;const MACOS_BACKDROP = { blur: 80, red: 0.07, green: 0.07, blue: 0.07, alpha: 0.9 };+// Window Controls Overlay on Windows: as tall as the renderer's `h-10` drag+// strip, coloured like the sidebar it sits on (`--sidebar` / `--foreground`).+const WINDOWS_OVERLAY_HEIGHT = 40;+const WINDOWS_OVERLAY_COLORS = {+ dark: { color: "#121212", symbolColor: "#f2f2f2" },+ light: { color: "#f7f7f7", symbolColor: "#161618" },+};// A Squirrel.Windows install/update/uninstall launch: housekeeping only, the// app quits on its own. Decided first so nothing below starts a service or@@ -91,6 +98,11 @@ function applyBackdrop() {setNativeBackdrop(mainWindow.getNativeWindowHandle(), blur, red, green, blue, alpha);}+function setColorMode(mode: "dark" | "light") {+ if (process.platform === "darwin" || !mainWindow || mainWindow.isDestroyed()) return;+ mainWindow.setTitleBarOverlay({ ...WINDOWS_OVERLAY_COLORS[mode], height: WINDOWS_OVERLAY_HEIGHT });+}+if (app.isPackaged && !squirrelLaunch && !process.argv.includes("--hidden")) {updateElectronApp({ repo: "diffusionstudio/editor" });}@@ -207,19 +219,36 @@ async function setFileInputFiles(selector: string, absolutePath: string) {}function createWindow(show = true) {- mainWindow = new BrowserWindow({++ const options: Electron.BrowserWindowConstructorOptions = {show: false,width: 1200,height: 800,- titleBarStyle: "hiddenInset",- trafficLightPosition: { x: 14, y: 14 },- ...(process.platform === "darwin"- ? { vibrancy: "sidebar" as const, backgroundColor: "#00000000" }- : { backgroundColor: "#1c1c1c" }),webPreferences: {preload: join(app.getAppPath(), "dist", "preload.js"),+ backgroundThrottling: false,},- });+ }++ if (process.platform === "darwin") {+ options.titleBarStyle = "hiddenInset" as const;+ options.trafficLightPosition = { x: 14, y: 14 };+ options.vibrancy = "sidebar" as const;+ options.backgroundColor = "#00000000";+ }++ if (process.platform === "win32") {+ options.titleBarStyle = "hidden" as const;+ options.titleBarOverlay = { ...WINDOWS_OVERLAY_COLORS.dark, height: WINDOWS_OVERLAY_HEIGHT };+ options.autoHideMenuBar = true;+ options.backgroundColor = WINDOWS_OVERLAY_COLORS.dark.color;++ if (!app.isPackaged) {+ options.icon = join(app.getAppPath(), "assets", "icon-dev.png");+ }+ }++ mainWindow = new BrowserWindow(options);captureConsole(mainWindow);@@ -300,6 +329,7 @@ if (squirrelLaunch) {takePendingDeepLink(MAIN_CHANNELS.CHECKOUT_CALLBACK),);mainBridge.handle(MAIN_CHANNELS.WINDOW_IS_FULLSCREEN, () => mainWindow?.isFullScreen() ?? false);+ mainBridge.handle(MAIN_CHANNELS.WINDOW_SET_COLOR_MODE, ({ mode }) => setColorMode(mode));mainBridge.handle(MAIN_CHANNELS.WINDOW_CAPTURE, async () => {if (!mainWindow || mainWindow.isDestroyed()) throw new Error("No main window");const image = await mainWindow.webContents.capturePage(undefined, { stayHidden: true });@@ -432,6 +462,7 @@ if (squirrelLaunch) {version: app.getVersion(),}),);+ refreshCliShim();healMcpRegistrations();trackInstall();createWindow(!isHiddenLaunch(process.argv));diff --git a/apps/desktop/src/mcp-config.test.ts b/apps/desktop/src/mcp-config.test.tsindex 8c4b357d..e98dfce5 100644--- a/apps/desktop/src/mcp-config.test.ts+++ b/apps/desktop/src/mcp-config.test.ts@@ -3,7 +3,16 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { describe, expect, it } from "vitest";-import { AGENT_TARGETS, agentTarget, needsBinary, readServer, removeServer, upsertServer } from "./mcp-config";+import {+ AGENT_TARGETS,+ agentTarget,+ needsBinary,+ readServer,+ removeServer,+ runsOurProxy,+ sameCommand,+ upsertServer,+} from "./mcp-config";const spec = {url: "http://127.0.0.1:3274/mcp",@@ -62,7 +71,7 @@ describe("json configs", () => {it("replaces a stdio entry with a URL entry, and reads either", () => {const before = upsertServer(null, "mcpServers", { command: "/old/dapi", args: ["mcp"] });- expect(readServer(before, "mcpServers")).toEqual({ command: "/old/dapi" });+ expect(readServer(before, "mcpServers")).toEqual({ command: "/old/dapi", args: ["mcp"] });const after = upsertServer(before, "mcpServers", { type: "http", url: spec.url });expect(readServer(after, "mcpServers")).toEqual({ url: spec.url });expect(JSON.parse(after).mcpServers.diffusion.command).toBeUndefined();@@ -114,7 +123,7 @@ describe("toml configs (codex)", () => {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" });+ expect(readServer(before, "toml")).toEqual({ command: "/old/dapi", args: ["mcp"] });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 });@@ -129,7 +138,7 @@ describe("toml configs (codex)", () => {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 });+ expect(readServer(text, "toml")).toEqual({ command: odd.command, args: ["mcp"] });});it("reads nothing from a config without our table", () => {@@ -152,3 +161,36 @@ describe("toml configs (codex)", () => {expect(removeServer(upsertServer(null, "toml", { url: spec.url }), "toml")).toBe("");});});++describe("stdio entries across platforms", () => {+ const shim = "C:\\Users\\me\\AppData\\Local\\DiffusionStudio\\bin\\dapi.cmd";+ const windows = { url: spec.url, command: "cmd", args: ["/c", shim, "mcp"] };++ it("keeps desktop apps' configs under appData and the dotfile agents under home", () => {+ expect(agentTarget("claude-desktop").config).toEqual({ root: "appData", path: "Claude/claude_desktop_config.json" });+ expect(agentTarget("vscode").config).toEqual({ root: "appData", path: "Code/User/mcp.json" });+ expect(AGENT_TARGETS.filter((t) => t.config.root === "appData").map((t) => t.id)).toEqual(["claude-desktop", "vscode"]);+ });++ it("round-trips the Windows shape, where the shim rides in args", () => {+ const entry = agentTarget("claude-desktop").entry(windows);+ expect(entry).toEqual({ command: "cmd", args: ["/c", shim, "mcp"] });+ const registered = readServer(upsertServer(null, "mcpServers", entry), "mcpServers");+ expect(registered).toEqual({ command: "cmd", args: ["/c", shim, "mcp"] });+ expect(sameCommand(registered!, entry)).toBe(true);+ });++ it("recognises our proxy by its path, as the command or as an argument", () => {+ expect(runsOurProxy({ command: spec.command, args: ["mcp"] })).toBe(true);+ expect(runsOurProxy({ command: "/private/var/folders/x/AppTranslocation/y/d/cli/bin/dapi" })).toBe(true);+ expect(runsOurProxy({ command: "cmd", args: ["/c", shim, "mcp"] })).toBe(true);+ expect(runsOurProxy({ command: "cmd", args: ["/c", "C:\\tools\\other.cmd"] })).toBe(false);+ expect(runsOurProxy({ command: "/opt/homebrew/bin/dapi", args: ["mcp"] })).toBe(false);+ });++ it("sees a moved shim as a different command", () => {+ const moved = { command: "cmd", args: ["/c", shim.replace("me", "you"), "mcp"] };+ expect(sameCommand(moved, agentTarget("claude-desktop").entry(windows))).toBe(false);+ expect(sameCommand({ command: spec.command, args: ["mcp"] }, agentTarget("claude-desktop").entry(spec))).toBe(true);+ });+});diff --git a/apps/desktop/src/mcp-config.ts b/apps/desktop/src/mcp-config.tsindex 90aa51ff..98917bae 100644--- a/apps/desktop/src/mcp-config.ts+++ b/apps/desktop/src/mcp-config.ts@@ -9,7 +9,9 @@/*** 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.+ * binary in stdio proxy mode. On Windows that binary is a `.cmd`, which+ * nothing can spawn without a shell, so the command is `cmd` and the shim's+ * path rides in `args`.*/export type McpServerSpec = { url: string; command: string; args: string[] };@@ -38,14 +40,22 @@ export type AgentId =/** How a config file spells its server map: JSON under `mcpServers` (or VS Code's `servers`), or Codex's TOML tables. */export type ConfigFormat = "mcpServers" | "servers" | "toml";+/**+ * A path under one of the two per-user roots. `appData` is where desktop apps+ * keep their files (Electron's `appData`: ~/Library/Application Support on+ * macOS, %APPDATA% on Windows), which keeps this table the same on every+ * platform; `mcp-install.ts` knows where the roots are.+ */+export type AgentPath = { root: "home" | "appData"; path: string };+export type AgentTarget = {id: AgentId;/** Human name, for the UI. */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;+ /** Path whose presence means the agent is set up on this machine. */+ marker: AgentPath;+ /** Path of the config file our entry goes into. */+ config: AgentPath;format: ConfigFormat;/** The entry for this agent: which transport it gets, under the keys its format uses. */entry(spec: McpServerSpec): ServerEntry;@@ -54,8 +64,8 @@ export type AgentTarget = {const http = (key: string, extra: ServerEntry = {}) => (spec: McpServerSpec): ServerEntry => ({ ...extra, [key]: spec.url });const stdio = (spec: McpServerSpec): ServerEntry => ({ command: spec.command, args: [...spec.args] });-/** Where macOS apps keep their per-user files; agents that are desktop apps put their config there. */-const APP_SUPPORT = "Library/Application Support";+const home = (path: string): AgentPath => ({ root: "home", path });+const appData = (path: string): AgentPath => ({ root: "appData", path });// Agents whose MCP config we know how to write, in the order the UI lists// them. Claude Code's user scope is the top-level `mcpServers` of@@ -65,28 +75,28 @@ const APP_SUPPORT = "Library/Application Support";// `serverUrl`. Claude Desktop's file takes stdio commands only, so it gets// the proxy.export const AGENT_TARGETS: readonly AgentTarget[] = [- { id: "claude-code", label: "Claude Code", marker: ".claude", config: ".claude.json", format: "mcpServers", entry: http("url", { type: "http" }) },+ { id: "claude-code", label: "Claude Code", marker: home(".claude"), config: home(".claude.json"), format: "mcpServers", entry: http("url", { type: "http" }) },{id: "claude-desktop",label: "Claude Desktop",- marker: `${APP_SUPPORT}/Claude`,- config: `${APP_SUPPORT}/Claude/claude_desktop_config.json`,+ marker: appData("Claude"),+ config: appData("Claude/claude_desktop_config.json"),format: "mcpServers",entry: stdio,},- { id: "cursor", label: "Cursor", marker: ".cursor", config: ".cursor/mcp.json", format: "mcpServers", entry: http("url") },+ { id: "cursor", label: "Cursor", marker: home(".cursor"), config: home(".cursor/mcp.json"), format: "mcpServers", entry: http("url") },{id: "vscode",label: "VS Code (Copilot)",- marker: `${APP_SUPPORT}/Code`,- config: `${APP_SUPPORT}/Code/User/mcp.json`,+ marker: appData("Code"),+ config: appData("Code/User/mcp.json"),format: "servers",entry: http("url", { type: "http" }),},- { id: "codex", label: "Codex", marker: ".codex", config: ".codex/config.toml", format: "toml", entry: http("url") },- { id: "antigravity", label: "Antigravity", marker: ".gemini/antigravity", config: ".gemini/config/mcp_config.json", format: "mcpServers", entry: http("serverUrl") },- { id: "gemini-cli", label: "Gemini CLI", marker: ".gemini", config: ".gemini/settings.json", format: "mcpServers", entry: http("httpUrl") },- { id: "windsurf", label: "Devin (Windsurf)", marker: ".codeium/windsurf", config: ".codeium/windsurf/mcp_config.json", format: "mcpServers", entry: http("serverUrl") },+ { id: "codex", label: "Codex", marker: home(".codex"), config: home(".codex/config.toml"), format: "toml", entry: http("url") },+ { id: "antigravity", label: "Antigravity", marker: home(".gemini/antigravity"), config: home(".gemini/config/mcp_config.json"), format: "mcpServers", entry: http("serverUrl") },+ { id: "gemini-cli", label: "Gemini CLI", marker: home(".gemini"), config: home(".gemini/settings.json"), format: "mcpServers", entry: http("httpUrl") },+ { id: "windsurf", label: "Devin (Windsurf)", marker: home(".codeium/windsurf"), config: home(".codeium/windsurf/mcp_config.json"), format: "mcpServers", entry: http("serverUrl") },];export function agentTarget(id: AgentId): AgentTarget {@@ -121,7 +131,7 @@ export function removeServer(text: string | null, format: ConfigFormat): 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 type Registered = { url?: string; command?: string; args?: string[] };export function readServer(text: string | null, format: ConfigFormat): Registered | null {if (text === null) return null;@@ -130,12 +140,40 @@ export function readServer(text: string | null, format: ConfigFormat): Registereconst url = entry.url ?? entry.httpUrl ?? entry.serverUrl;const command = entry.command;if (typeof url !== "string" && typeof command !== "string") return null;+ const args = Array.isArray(entry.args) ? entry.args.filter((arg): arg is string => typeof arg === "string") : null;return {...(typeof url === "string" ? { url } : {}),...(typeof command === "string" ? { command } : {}),+ ...(typeof command === "string" && args ? { args } : {}),};}+// What a path to our proxy has in it: the app's name inside a macOS bundle+// (or the translocated mount a quarantined bundle ran from), the Squirrel+// package id in the Windows shim folder.+const OUR_PATHS = ["Diffusion Studio", "/AppTranslocation/", "\\DiffusionStudio\\"];++/**+ * Whether a stdio entry runs our proxy — from wherever the app was when the+ * entry was written — rather than something the user put under our name by+ * hand. The path is the command itself, or on Windows an argument to `cmd`.+ */+export function runsOurProxy(registered: Registered): boolean {+ return [registered.command ?? "", ...(registered.args ?? [])].some((part) =>+ OUR_PATHS.some((marker) => part.includes(marker)),+ );+}++/** Whether a stdio entry already is what `entry` would write. */+export function sameCommand(registered: Registered, entry: ServerEntry): boolean {+ const args = Array.isArray(entry.args) ? entry.args : [];+ return (+ registered.command === entry.command &&+ (registered.args ?? []).length === args.length &&+ (registered.args ?? []).every((arg, index) => arg === args[index])+ );+}+// --- JSON ------------------------------------------------------------------type JsonFormat = Exclude<ConfigFormat, "toml">;diff --git a/apps/desktop/src/mcp-install.ts b/apps/desktop/src/mcp-install.tsindex c9087ec3..16fb2dae 100644--- a/apps/desktop/src/mcp-install.ts+++ b/apps/desktop/src/mcp-install.ts@@ -13,36 +13,71 @@ 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";-import { AGENT_TARGETS, agentTarget, needsBinary, readServer, removeServer, upsertServer } from "./mcp-config";--import type { AgentTarget, McpServerSpec } from "./mcp-config";+import { shimPath } from "./cli-windows";+import {+ AGENT_TARGETS,+ agentTarget,+ needsBinary,+ readServer,+ removeServer,+ runsOurProxy,+ sameCommand,+ upsertServer,+} from "./mcp-config";++import type { AgentPath, AgentTarget, McpServerSpec } from "./mcp-config";import type { McpAgentStatus, McpApplyRequest, McpApplyResult, McpStatus } from "./main-channels";// 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). */+/**+ * The bundled `dapi` binary, or null when none is available (an unstaged dev+ * build). On Windows it is the shim outside the install folder, the one path+ * that survives an update; a packaged app writes it on every launch, so it+ * counts as there even in the moment before that write lands.+ */export function dapiBinary(): string | null {+ if (process.platform === "win32") {+ const shim = shimPath();+ return app.isPackaged || existsSync(shim) ? shim : 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"] };+ const binary = dapiBinary();+ if (!binary) {+ return { url: MCP_URL, command: "", args: [] };+ }+ // A `.cmd` only runs through a shell, and the agents spawn without one.+ if (process.platform === "win32") {+ return { url: MCP_URL, command: "cmd", args: ["/c", binary, "mcp"] };+ }++ return { url: MCP_URL, command: binary, args: ["mcp"] };}-function configPath(target: AgentTarget): string {- return join(homedir(), target.config);+function resolvePath(location: AgentPath): string {+ if (location.root === "home") {+ return join(homedir(), location.path);+ }+ if (location.root === "appData") {+ return join(app.getPath("appData"), location.path);+ }++ throw new Error(`Unknown agent path root: ${location.root}`);}function readConfig(target: AgentTarget): string | null {- const path = configPath(target);+ const path = resolvePath(target.config);return existsSync(path) ? readFileSync(path, "utf8") : null;}function writeConfig(target: AgentTarget, text: string): void {- const path = configPath(target);+ const path = resolvePath(target.config);mkdirSync(dirname(path), { recursive: true });writeFileSync(path, text);}@@ -68,9 +103,9 @@ function agentStatus(target: AgentTarget, current: McpServerSpec): McpAgentStatureturn {id: target.id,label: target.label,- detected: existsSync(join(homedir(), target.marker)),+ detected: existsSync(resolvePath(target.marker)),connected: registered !== null,- config: configPath(target),+ config: resolvePath(target.config),unavailable: unavailableReason(target, current),};}@@ -101,7 +136,7 @@ export function applyMcp(request: McpApplyRequest): McpApplyResult {writeConfig(target, upsertServer(readConfig(target), target.format, target.entry(current)));result.added.push(id);} catch (e) {- result.failures.push({ id, error: `${target.config}: ${(e as Error).message}` });+ result.failures.push({ id, error: `${target.config.path}: ${(e as Error).message}` });}}@@ -112,7 +147,7 @@ export function applyMcp(request: McpApplyRequest): McpApplyResult {if (next !== null) writeConfig(target, next);result.removed.push(id);} catch (e) {- result.failures.push({ id, error: `${target.config}: ${(e as Error).message}` });+ result.failures.push({ id, error: `${target.config.path}: ${(e as Error).message}` });}}@@ -134,10 +169,10 @@ export function healMcpRegistrations(): void {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;+ if (!runsOurProxy(registered)) continue;const entry = target.entry(current);- if (registered.command === entry.command) continue;+ if (sameCommand(registered, entry)) continue;+try {writeConfig(target, upsertServer(text, target.format, entry));} catch {diff --git a/apps/desktop/src/menu.ts b/apps/desktop/src/menu.tsindex 25c54e01..c592297a 100644--- a/apps/desktop/src/menu.ts+++ b/apps/desktop/src/menu.ts@@ -6,10 +6,13 @@ import { app, Menu } from "electron";import type { MenuItemConstructorOptions } from "electron";export function setupAppMenu() {- if (process.platform !== "darwin") return;+ // The app submenu is a macOS convention. Elsewhere the same role menus sit+ // behind Alt (the window hides the bar) and exist for their accelerators:+ // reload, devtools, zoom, quit.+ const template: MenuItemConstructorOptions[] = []- const template: MenuItemConstructorOptions[] = [- {+ if (process.platform === "darwin") {+ template.push({label: app.name,submenu: [{ role: "about" },@@ -22,12 +25,15 @@ export function setupAppMenu() {{ type: "separator" },{ role: "quit" },],- },+ });+ }++ template.push({ role: "fileMenu" },{ role: "editMenu" },{ role: "viewMenu" },{ role: "windowMenu" },- ];+ );Menu.setApplicationMenu(Menu.buildFromTemplate(template));}diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 70082180..71a8b708 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -17,6 +17,7 @@ import type { PluginItem, TransformOptions } from "@babel/core";import type { BuildOptions, Plugin } from "esbuild";import { isTempPath, TEMP_PREFIX, writeFileAtomic } from "./atomic";+import { windowsCloudSyncKind } from "./cloud-sync-windows";import { isHeadless } from "./headless";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";@@ -318,18 +319,8 @@ export async function cloudSyncKind(path: string): Promise<string | null> {const mobile = await resolveDeepest(join(home, "Library", "Mobile Documents"));if (real === mobile || real.startsWith(mobile + sep)) return "iCloud Drive";- // Windows has no File Provider to ask.- if (process.platform === "win32") {- const roots: Array<[string, string]> = [[join(home, "iCloudDrive"), "iCloud Drive"]];- for (const key of ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]) {- const dir = process.env[key];- if (dir) roots.push([dir, "OneDrive"]);- }- for (const [dir, label] of roots) {- const root = resolve(dir);- if (real === root || real.startsWith(root + sep)) return label;- }- }+ // Windows has no File Provider to ask; everything below is macOS.+ if (process.platform === "win32") return windowsCloudSyncKind(real, home);// The home Desktop and Documents, before the attribute is asked for: it is// the one the app is most likely to be unable to read.diff --git a/apps/desktop/src/squirrel.ts b/apps/desktop/src/squirrel.tsindex 75811b9c..f77527bb 100644--- a/apps/desktop/src/squirrel.ts+++ b/apps/desktop/src/squirrel.ts@@ -6,14 +6,20 @@// uninstall, with a `--squirrel-*` flag as the only argument, and expects it// to do its housekeeping and exit. That is the moment the Start Menu// shortcut is created and removed (through Squirrel's own Update.exe, one-// folder up from the versioned app folder), and — from later stages — where-// the `dapi` shim and the agents' MCP entries get written and cleaned up.+// folder up from the versioned app folder), where the `dapi` shim is pointed+// at the new version and taken away again, and where the agents' MCP entries+// are taken out of their configs so no agent is left calling an app that is+// gone.// `--squirrel-firstrun` is the ordinary first launch and is not an event.import { app } from "electron";import { spawn } from "node:child_process";import { basename, resolve } from "node:path";+import { removeShim, removeShimFromPath, writeShim } from "./cli-windows";+import { AGENT_TARGETS } from "./mcp-config";+import { applyMcp } from "./mcp-install";+const EVENTS = new Set(["--squirrel-install", "--squirrel-updated", "--squirrel-uninstall", "--squirrel-obsolete"]);/** The `--squirrel-*` event this launch is, or null when it is a real launch. */@@ -50,10 +56,20 @@ export function handleSquirrelEvent(): boolean {switch (event) {case "--squirrel-install":case "--squirrel-updated":- updateExe(["--createShortcut", target]);+ writeShim()+ .catch(() => { })+ .then(() => updateExe(["--createShortcut", target]));break;case "--squirrel-uninstall":- updateExe(["--removeShortcut", target]);+ try {+ applyMcp({ add: [], remove: AGENT_TARGETS.map((target) => target.id) });+ } catch {/* best effort */ }++ removeShimFromPath()+ .catch(() => { })+ .then(() => removeShim())+ .catch(() => { })+ .then(() => updateExe(["--removeShortcut", target]));break;default:// --squirrel-obsolete: the version being replaced gets a last word; we have none.diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsxindex 171fbdc1..ef797f42 100644--- a/apps/web/src/app.tsx+++ b/apps/web/src/app.tsx@@ -10,6 +10,9 @@ import { AppContextMenu } from "@/components/app-context-menu";import { AuthProvider, useAuth } from '@/context/auth';import { PersistRoute } from '@/lib/persist-route';+import { useColorMode } from "@kobalte/core";+import { mainBridge } from "@/lib/ipc";+import { MAIN_CHANNELS } from "@desktop/main-channels";import { EditorApi } from '@/dapi';import { UpgradeDialog } from '@/components/upgrade-dialog';import { PurchaseSuccess } from '@/components/purchase-success';@@ -47,6 +50,18 @@ function BootSplash() {return null;}+function TitleBarColorMode() {+ const { colorMode } = useColorMode();++ createEffect(() => {+ if (window.desktop?.platform === "win32") {+ mainBridge.call(MAIN_CHANNELS.WINDOW_SET_COLOR_MODE, { mode: colorMode() });+ };+ });++ return null;+}+function EnvironmentOverlays() {const location = useLocation();const onCheckoutPage = () => location.pathname.startsWith('/checkout');@@ -77,6 +92,7 @@ function App() {<Toaster /><EnvironmentOverlays /><PersistRoute />+ <TitleBarColorMode /></ColorModeProvider>)}>diff --git a/apps/web/src/components/dashboard/mcp-view.tsx b/apps/web/src/components/dashboard/mcp-view.tsxindex 013f9f8e..3e075f4d 100644--- a/apps/web/src/components/dashboard/mcp-view.tsx+++ b/apps/web/src/components/dashboard/mcp-view.tsx@@ -211,8 +211,12 @@ function DashboardCliSection() {setBusy(true);try {const result = await installCli();- if (result.status === "installed") toast("CLI installed", { description: "Run dapi --help in a terminal to get started." });- if (result.status === "error") toast.error("Could not install the CLI", { description: result.error });+ if (result.status === "installed") {+ toast("CLI installed", { description: "Run dapi --help in a terminal to get started." });+ }+ if (result.status === "error") {+ toast.error("Could not install the CLI", { description: result.error });+ }} catch (e) {toast.error("Could not install the CLI", { description: (e as Error).message });} finally {diff --git a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsxindex 3b00f62a..ad161f64 100644--- a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx+++ b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx@@ -24,7 +24,7 @@ export function InspectorHeader() {const zoomLabel = () => `${Math.round(scale() * 100)}%`;return (- <div class="h-12 shrink-0 flex items-center px-4">+ <div class="h-12 shrink-0 flex items-center pl-4 pr-[calc(1rem+var(--titlebar-controls-width))]"><span class="text-[12px] leading-5 font-450 text-foreground">Editor</span><DropdownMenu placement="bottom-end"><DropdownMenuTrigger<typeof Button>diff --git a/apps/web/src/dapi/handler.ts b/apps/web/src/dapi/handler.tsindex 882165bf..b38372bd 100644--- a/apps/web/src/dapi/handler.ts+++ b/apps/web/src/dapi/handler.ts@@ -31,6 +31,6 @@ export type ToolContext = {export type ToolHandler<N extends ToolName> = (args: ToolArgs<N>, ctx: ToolContext) => Promise<ToolResult<N>>;/** The tools the renderer answers; the rest run in the main process. */-export type ServedToolName = Exclude<ToolName, "logs" | "fonts" | "report">;+export type ServedToolName = Exclude<ToolName, "logs" | "report">;export type Handlers = { readonly [N in ServedToolName]: ToolHandler<N> };diff --git a/apps/web/src/dapi/handlers/fonts.ts b/apps/web/src/dapi/handlers/fonts.tsnew file mode 100644index 00000000..9414645f--- /dev/null+++ b/apps/web/src/dapi/handlers/fonts.ts@@ -0,0 +1,49 @@+/* 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 { DapiError, FONT_LIMIT } from "@diffusionstudio/dapi";+import { FontStyle } from "@diffusionstudio/runtime";+import { getLocalFonts } from "@/engine/fonts";++import type { FontFamily } from "@diffusionstudio/dapi";+import type { ToolHandler } from "../handler";++/**+ * The machine's fonts, from the same Local Font Access listing the text+ * inspector shows, so the tool answers alike on every platform and names+ * exactly the families the editor can render. The catalog knows two styles;+ * an oblique is an italic to anyone choosing a font.+ */+export const fonts: ToolHandler<"fonts"> = async ({ family, weights, style, limit = FONT_LIMIT }) => {+ const pattern = family?.toLowerCase();+ const wanted = weights && weights.length > 0 ? new Set(weights) : null;++ const local = await getLocalFonts().catch((e: Error) => {+ throw new DapiError("unsupported", `The local fonts could not be listed: ${e.message}`);+ });++ const families: FontFamily[] = [];+ for (const entry of local) {+ if (entry.family.startsWith(".") || (pattern && !entry.family.toLowerCase().includes(pattern))) continue;++ const variants = entry.variants+ .map((v) => ({+ weight: v.weight ?? "400",+ style: v.style === FontStyle.NORMAL ? ("normal" as const) : ("italic" as const),+ source: v.source,+ }))+ .filter((v) => (!wanted || wanted.has(v.weight)) && (!style || v.style === style));++ if (variants.length > 0) {+ families.push({+ family: entry.family,+ variants+ });+ };+ }++ families.sort((a, b) => a.family.localeCompare(b.family));++ return { families: families.slice(0, limit), total: families.length };+};diff --git a/apps/web/src/dapi/handlers/index.ts b/apps/web/src/dapi/handlers/index.tsindex 9aa95a0b..56e8baac 100644--- a/apps/web/src/dapi/handlers/index.ts+++ b/apps/web/src/dapi/handlers/index.ts@@ -9,6 +9,7 @@ import { check } from "./check";import { exportScene } from "./export";import { models } from "./models";import { voices } from "./voices";+import { fonts } from "./fonts";import { whoami } from "./whoami";import { screenshot } from "./screenshot";import { mediaProbe } from "./media-probe";@@ -29,6 +30,7 @@ export const handlers: Handlers = {export: exportScene,models,voices,+ fonts,whoami,screenshot,media_probe: mediaProbe,diff --git a/apps/web/src/engine/fonts.ts b/apps/web/src/engine/fonts.tsindex 936c3cb5..79101c00 100644--- a/apps/web/src/engine/fonts.ts+++ b/apps/web/src/engine/fonts.ts@@ -2,13 +2,6 @@* 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/. */-/**- * The half of the font story that needs a browser the runtime cannot assume:- * the machine's own families, behind the Local Font Access API. Web fonts and- * loading live in `@diffusionstudio/runtime` (`getWebFonts`, `loadWebFont`),- * which the CLI shares.- */-import { FontStyle } from '@diffusionstudio/runtime';import type { FontSources } from '@diffusionstudio/runtime';@@ -58,12 +51,12 @@ function matchFontStyle(style: string): FontStyle {function matchFontWeight(weight: string): string {const matches: [RegExp, string][] = [[/black|heavy/i, '900'],- [/extrabold|ultrabold/i, '800'],- [/semibold|demibold/i, '600'],+ [/(extra|ultra)[ -]?bold/i, '800'],+ [/(semi|demi)[ -]?bold/i, '600'],[/bold|strong/i, '700'],[/medium/i, '500'],[/normal|regular|book|plain/i, '400'],- [/extralight|ultralight/i, '200'],+ [/(extra|ultra)[ -]?light/i, '200'],[/thin|hairline/i, '100'],[/light/i, '300'],];diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 34f92ef5..50ff89c4 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -224,6 +224,14 @@--meter-clip: hsla(60, 100%, 50%, 1);}+/* Windows desktop: the native minimize/maximize/close buttons overlay the+ top-right corner. Chromium reports the free part of the title bar through+ the titlebar-area variables, so this is the width the controls take at any+ DPI, and 0 wherever there is no overlay (web, macOS, fullscreen). */+:root {+ --titlebar-controls-width: calc(100vw - env(titlebar-area-x, 0px) - env(titlebar-area-width, 100vw));+}+/* macOS desktop: the BrowserWindow uses native vibrancy, so the page keeps atransparent background and the sidebars go translucent to let the blur show. */[data-platform="darwin"],diff --git a/docs/reference/jsx/fonts.md b/docs/reference/jsx/fonts.mdindex edb0d727..48c8909d 100644--- a/docs/reference/jsx/fonts.md+++ b/docs/reference/jsx/fonts.md@@ -1,6 +1,6 @@# Fonts-Both text paths draw with fonts **installed on the machine**. Discover what is available with [`fonts`](../tools/fonts.md) (filter by family, weight, or style); the active project's families are also on [`context`](../tools/context.md) as `fontFamilies`. macOS resolves these families for both the native renderer and the browser, so there is nothing to bundle or load.+Both text paths draw with fonts **installed on the machine**. Discover what is available with [`fonts`](../tools/fonts.md) (filter by family, weight, or style); the active project's families are also on [`context`](../tools/context.md) as `fontFamilies`.## Native `<text>`diff --git a/docs/reference/tools/README.md b/docs/reference/tools/README.mdindex 5fe332a9..f2380d40 100644--- a/docs/reference/tools/README.md+++ b/docs/reference/tools/README.md@@ -26,7 +26,7 @@ Every tool returns one JSON object, its *structured content*. Over MCP that is tA failure is a sentence written to be read, e.g. `No project open — run open first`. Over MCP it arrives as a tool result with `isError: true`, not as a protocol error; the CLI prints it to stderr and exits `1`. Each page's Errors section lists what the tool fails on; only the delivery differs by surface.-Every tool runs inside the app, so the app has to be running. Over MCP that is a given — the connection is to the app. From a shell, `dapi open` launches it (macOS) or surfaces the running instance; every other command prints a launch instruction and exits `1` while the app is down.+Every tool runs inside the app, so the app has to be running. Over MCP that is a given — the connection is to the app. From a shell, `dapi open` launches it (macOS and Windows) or surfaces the running instance; every other command prints a launch instruction and exits `1` while the app is down.## The toolsdiff --git a/docs/reference/tools/fonts.md b/docs/reference/tools/fonts.mdindex 180d2dd8..eddadcf1 100644--- a/docs/reference/tools/fonts.md+++ b/docs/reference/tools/fonts.md@@ -1,6 +1,6 @@# fonts-List the local fonts available on this machine (macOS only). These family names are valid `fontFamily` values on <text>; each family lists its variants.+List the local fonts available on this machine. These family names are valid `fontFamily` values on <text>; each family lists its variants.| | || --- | --- |@@ -16,7 +16,7 @@ List the local fonts available on this machine (macOS only). These family names| `style` | `"normal" \| "italic"` | `-s, --style <style>` | filter to variants with the given style, normal or italic || `limit` | `integer` | `-l, --limit <n>` | return at most this many families (default: 50) |-Font families listed here are valid `fontFamily` values on [`<text>`](../jsx/text.md); see [jsx/fonts.md](../jsx/fonts.md) for how a family and variant are named in a composition, and [`context`](./context.md) for the families the open project has actually registered. Runs in the app's main process, so no project needs to be open.+Font families listed here are valid `fontFamily` values on [`<text>`](../jsx/text.md); see [jsx/fonts.md](../jsx/fonts.md) for how a family and variant are named in a composition, and [`context`](./context.md) for the families the open project has actually registered.A machine has hundreds of families, so filter by `family` when looking for one. `total` counts every family the filters match; when it is larger than `families.length`, the limit cut the list.diff --git a/docs/reference/tools/open.md b/docs/reference/tools/open.mdindex fd3bb83a..59f1b68c 100644--- a/docs/reference/tools/open.md+++ b/docs/reference/tools/open.md@@ -28,7 +28,7 @@ The app remembers the folder, so the project reopens across app relaunches and s## From a shell-`dapi open` is also how the app starts: it launches Diffusion Studio (macOS) or surfaces the running instance, then, given a path, calls the tool. With no path it only makes sure the app is up, printing nothing and exiting `0` once the app answers. Relative paths resolve against the shell's working directory. `--background` launches or keeps the app without raising a window — the way to drive the editor headless.+`dapi open` is also how the app starts: it launches Diffusion Studio (macOS and Windows) or surfaces the running instance, then, given a path, calls the tool. With no path it only makes sure the app is up, printing nothing and exiting `0` once the app answers. Relative paths resolve against the shell's working directory. `--background` launches or keeps the app without raising a window — the way to drive the editor headless.Over MCP the app is already running, since that is what the connection is to; the tool only opens the folder, and `dir` must be absolute.@@ -48,4 +48,4 @@ The opened project:- The path is not absolute (`The project folder must be an absolute path`).- The path exists but is not a folder.-- From a shell off macOS, the app cannot be launched; the command then requires it to already be running.+- From a shell on Linux, or from a `dapi` that is not the one the app ships (a workspace build on Windows), the app cannot be launched; the command then requires it to already be running.diff --git a/packages/dapi/src/catalog.test.ts b/packages/dapi/src/catalog.test.tsindex 225146d9..77199df9 100644--- a/packages/dapi/src/catalog.test.ts+++ b/packages/dapi/src/catalog.test.ts@@ -47,7 +47,8 @@ describe("catalog", () => {it("looks tools up by name", () => {expect(toolByName("capture").environment).toBe("renderer");- expect(toolByName("fonts").environment).toBe("main");+ expect(toolByName("fonts").environment).toBe("renderer");+ expect(toolByName("logs").environment).toBe("main");expect(isToolName("media_grab")).toBe(true);expect(isToolName("media.frame")).toBe(false);});diff --git a/packages/dapi/src/tools/fonts.ts b/packages/dapi/src/tools/fonts.tsindex 3d0d0cdf..b661d246 100644--- a/packages/dapi/src/tools/fonts.ts+++ b/packages/dapi/src/tools/fonts.ts@@ -25,7 +25,7 @@ export const fonts = defineTool({name: "fonts",title: "Local fonts",description:- "List the local fonts available on this machine (macOS only). These family names are valid `fontFamily` values on <text>; each family lists its variants. A machine has hundreds of families, so filter by family name when looking for one; total tells whether the limit cut the list.",+ "List the local fonts available on this machine. These family names are valid `fontFamily` values on <text>; each family lists its variants. A machine has hundreds of families, so filter by family name when looking for one; total tells whether the limit cut the list.",input: z.object({family: z.string().optional().describe("filter to families whose name contains this (case-insensitive)"),weights: z.array(z.string()).optional().describe('filter to variants with the given CSS weights, e.g. ["400", "700"]'),@@ -36,5 +36,5 @@ export const fonts = defineTool({families: z.array(FontFamily),total: z.int().describe("families matching the filters before the limit; more than were returned means the list was cut"),}),- environment: "main",+ environment: "renderer",});diff --git a/scripts/dev-desktop.mjs b/scripts/dev-desktop.mjsindex d09a86ee..727e1cd3 100644--- a/scripts/dev-desktop.mjs+++ b/scripts/dev-desktop.mjs@@ -20,6 +20,7 @@ const ROOT = fileURLToPath(new URL("..", import.meta.url));const BIN = join(ROOT, "node_modules", ".bin");const DEV_PORT = 5173;const DEV_URL = `http://localhost:${DEV_PORT}`;+const WINDOWS = process.platform === "win32";const children = [];let shuttingDown = false;@@ -27,8 +28,12 @@ function run(name, bin, args, cwd) {// Spawn the tool binary directly rather than via `npm run`, so the teardown// SIGTERM isn't dressed up as a "Lifecycle script failed" error by an npm// wrapper. Own process group (detached) so we can signal the tool *and* its- // children (esbuild, electron) in one shot on teardown.- const child = spawn(join(BIN, bin), args, { cwd, stdio: "inherit", detached: true });+ // children (esbuild, electron) in one shot on teardown. Windows has neither+ // groups nor spawnable `.cmd` shims: the shim runs through a shell, stays in+ // this console, and `taskkill /T` takes the tree down instead.+ const child = WINDOWS+ ? spawn(`"${join(BIN, `${bin}.cmd`)}"`, args, { cwd, stdio: "inherit", shell: true })+ : spawn(join(BIN, bin), args, { cwd, stdio: "inherit", detached: true });child.on("exit", (code) => {if (shuttingDown) return;// A child dying on its own (e.g. Vite crashed) should bring the rest down.@@ -39,16 +44,21 @@ function run(name, bin, args, cwd) {return child;}+/** Stops a process and everything under it. */+function killTree(pid, signal = "SIGTERM") {+ try {+ if (WINDOWS) execFileSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });+ else process.kill(pid, signal);+ } catch {+ // Already gone.+ }+}+function shutdown(code) {if (shuttingDown) return;shuttingDown = true;- for (const child of children) {- try {- process.kill(-child.pid, "SIGTERM");- } catch {- // Already gone.- }- }+ // A negative pid signals the child's whole process group.+ for (const child of children) killTree(WINDOWS ? child.pid : -child.pid);process.exit(code);}@@ -80,8 +90,24 @@ for (const signal of ["SIGINT", "SIGTERM"]) {process.on(signal, () => shutdown(0));}-/** PIDs listening on a TCP port (macOS/Linux via lsof); [] when none or unknown. */+/** PIDs listening on a TCP port (lsof, or netstat on Windows); [] when none or unknown. */function listeners(port) {+ if (WINDOWS) {+ try {+ // ` TCP [::1]:5173 [::]:0 LISTENING 1234`+ const out = execFileSync("netstat", ["-ano", "-p", "TCP"], { stdio: ["ignore", "pipe", "ignore"] }).toString();+ const v6 = execFileSync("netstat", ["-ano", "-p", "TCPv6"], { stdio: ["ignore", "pipe", "ignore"] }).toString();+ const pids = `${out}\n${v6}`+ .split("\n")+ .map((line) => line.trim().split(/\s+/))+ .filter((cols) => cols[0] === "TCP" && cols[3] === "LISTENING" && cols[1]?.endsWith(`:${port}`))+ .map((cols) => Number(cols[4]))+ .filter(Boolean);+ return [...new Set(pids)];+ } catch {+ return [];+ }+ }try {const out = execFileSync("lsof", ["-nP", "-t", `-iTCP:${port}`, "-sTCP:LISTEN"], { stdio: ["ignore", "pipe", "ignore"] });return out.toString().split("\n").map((line) => Number(line.trim())).filter(Boolean);@@ -92,6 +118,14 @@ function listeners(port) {/** The command line of a process, or "" when it is gone. */function commandOf(pid) {+ if (WINDOWS) {+ try {+ const query = `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`;+ return execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", query], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();+ } catch {+ return "";+ }+ }try {return execFileSync("ps", ["-o", "command=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();} catch {@@ -99,6 +133,13 @@ function commandOf(pid) {}}+/** Whether a command line is a Vite started from this checkout. Windows paths compare without case. */+function isOurVite(command) {+ const root = ROOT.replace(/[\\/]$/, "");+ const [haystack, needle] = WINDOWS ? [command.toLowerCase(), root.toLowerCase()] : [command, root];+ return haystack.includes("vite") && haystack.includes(needle);+}+/*** Frees the dev port. A Vite left over from an earlier run of this repo* (Ctrl-C'd terminal, crashed Electron, a detached child) is killed and the@@ -110,23 +151,17 @@ async function reclaimPort(port) {if (!pids.length) return;for (const pid of pids) {const command = commandOf(pid);- if (!command.includes("vite") || !command.includes(ROOT.replace(/\/$/, ""))) {+ if (!isOurVite(command)) {console.error(`[dev:desktop] port ${port} is in use by another process (pid ${pid}): ${command || "unknown"}`);process.exit(1);}console.log(`[dev:desktop] port ${port} held by a stale vite (pid ${pid}); stopping it…`);- try {- process.kill(pid, "SIGTERM");- } catch {- // Already gone.- }+ killTree(pid);}const deadline = Date.now() + 5000;while (listeners(port).length) {if (Date.now() > deadline) {- for (const pid of listeners(port)) {- try { process.kill(pid, "SIGKILL"); } catch { /* gone */ }- }+ for (const pid of listeners(port)) killTree(pid, "SIGKILL");await new Promise((r) => setTimeout(r, 200));break;}