The VS Code of video editing, built for agents.
TypeScript
Enhance CLI and Desktop Functionality
konstantin-paulusd2f0ecb1de0c
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex ecff18fc..2ad078e9 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -105,7 +105,9 @@ program.argument("[path]", `${field("open", "dir")} (default: none — just launch the app)`).option("-b, --background", "launch or keep the app in the background, without raising a window").action(async (path: string | undefined, opts: { background?: boolean }) => {- const launched = await launchApp(opts.background ?? false);+ const background = opts.background ?? false;+ const running = background && (await ping().then(() => true, (e) => (isAppDown(e) ? false : appError(e))));+ const launched = !running && (await launchApp(background));await (launched ? waitForApp() : ping()).catch(appError);if (path !== undefined) await run("open", { dir: resolve(path) });});@@ -276,6 +278,15 @@ program.option("-o, --output <dir>", field("screenshot", "output")).action((opts: ToolInput<"screenshot">) => run("screenshot", { output: opts.output && resolve(opts.output) }));+program+ .command("window")+ .description(describe("window"))+ .argument("[state]", "show (and focus) or hide the window (default: leave it as it is)")+ .action((state: string | undefined) => {+ if (state !== undefined && state !== "show" && state !== "hide") fail(`Expected show or hide, got "${state}".`);+ return run("window", { visible: state === undefined ? undefined : state === "show" });+ });+program.command("report").alias("issue")diff --git a/apps/desktop/assets/tray/busyTemplate.png b/apps/desktop/assets/tray/busyTemplate.pngnew file mode 100644index 00000000..fd73c852Binary files /dev/null and b/apps/desktop/assets/tray/busyTemplate.png differdiff --git a/apps/desktop/assets/tray/[email protected] b/apps/desktop/assets/tray/[email protected]new file mode 100644index 00000000..fe193436Binary files /dev/null and b/apps/desktop/assets/tray/[email protected] differdiff --git a/apps/desktop/assets/tray/idleTemplate.png b/apps/desktop/assets/tray/idleTemplate.pngnew file mode 100644index 00000000..d482c7d0Binary files /dev/null and b/apps/desktop/assets/tray/idleTemplate.png differdiff --git a/apps/desktop/assets/tray/[email protected] b/apps/desktop/assets/tray/[email protected]new file mode 100644index 00000000..df0f26b0Binary files /dev/null and b/apps/desktop/assets/tray/[email protected] differdiff --git a/apps/desktop/assets/tray/win.png b/apps/desktop/assets/tray/win.pngnew file mode 100644index 00000000..f706d103Binary files /dev/null and b/apps/desktop/assets/tray/win.png differdiff --git a/apps/desktop/assets/tray/[email protected] b/apps/desktop/assets/tray/[email protected]new file mode 100644index 00000000..37a59b16Binary files /dev/null and b/apps/desktop/assets/tray/[email protected] differdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex ee461b09..2415730b 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -10,7 +10,7 @@"main": "dist/main.js","scripts": {"build:preload": "esbuild src/preload.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist/preload.js",- "build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js",+ "build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --loader:.png=binary --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js","build:native": "node scripts/build-native.mjs","build": "npm run check && npm run build:main && npm run build:preload && npm run build:agent-host && npm run build:native","build:web": "npm --prefix ../web run build:desktop",diff --git a/apps/desktop/src/agent-chat.ts b/apps/desktop/src/agent-chat.tsindex c8196999..ef07cc23 100644--- a/apps/desktop/src/agent-chat.ts+++ b/apps/desktop/src/agent-chat.ts@@ -2,12 +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 agent chat host as a utility process: forked from the ESM bundle-// esbuild puts in dist/, configured over parentPort (never argv, which-// every process can read), restarted with backoff when it dies. The-// renderer asks for the endpoint over the existing IPC and talks to the-// host over its own WebSocket from there.-import { app, utilityProcess } from "electron";import { randomBytes } from "node:crypto";import { join } from "node:path";@@ -19,6 +13,8 @@ type AgentChatOptions = { dataDir: string; mcpUrl: string | null; version: strinconst DEV_ORIGIN = "http://localhost:5173";const RESTART_DELAYS_MS = [1000, 2000, 5000, 10_000];const STOP_GRACE_MS = 3000;+// How long an ask for the endpoint waits for a host it had to start.+const START_WAIT_MS = 10_000;let child: UtilityProcess | null = null;let endpoint: { url: string } | null = null;@@ -28,6 +24,8 @@ let restarts = 0;let restartTimer: ReturnType<typeof setTimeout> | null = null;let stopped = false;+const waiting = new Set<() => void>();+function spawn(): void {if (!options || stopped) return;const path = join(app.getAppPath(), "dist", "agent-host.mjs");@@ -51,6 +49,9 @@ function spawn(): void {if (message?.type === "listening" && typeof message.url === "string") {endpoint = { url: message.url };restarts = 0;+ for (const wake of [...waiting]) {+ wake();+ }console.log(`[agent-chat] host listening at ${message.url.replace(/token=.*$/, "token=…")}`);} else if (message?.type === "error") {console.error(`[agent-chat] host failed to start: ${message.message}`);@@ -72,23 +73,43 @@ function spawn(): void {});}-/** Generates the token and forks the host. Call once, after `whenReady`. */-export function startAgentChat(next: AgentChatOptions): void {+/** Generates the token; the host is forked when it is first needed. Call once, after `whenReady`. */+export function configureAgentChat(next: AgentChatOptions): void {options = next;token = randomBytes(32).toString("base64url");stopped = false;restarts = 0;- spawn();}-/** Where the host is right now: null while it is (re)starting. */-export function agentChatEndpoint(): { url: string } | null {- return endpoint;+/** Where the host is listening, starting it when it is not running; null when it does not come up in time. */+export function agentChatEndpoint(): Promise<{ url: string } | null> {+ if (endpoint || stopped || !options) {+ return Promise.resolve(endpoint);+ }+ // Not running and not about to restart: this is the first ask.+ if (!child && !restartTimer) {+ spawn();+ }++ return new Promise((resolve) => {+ const wake = () => {+ clearTimeout(timer);+ waiting.delete(wake);+ resolve(endpoint);+ };+ const timer = setTimeout(wake, START_WAIT_MS);+ waiting.add(wake);+ });}-/** Best effort: a host that is down or restarting leaves the chats behind. They aren't trashed with the folder. */-export function deleteProjectChats(projectId: string): void {- if (projectId && endpoint) child?.postMessage({ type: "deleteProject", projectId });+/** Best effort: a host that does not come up leaves the chats behind. They aren't trashed with the folder. */+export async function deleteProjectChats(projectId: string): Promise<void> {+ if (!projectId) return;+ const running = await agentChatEndpoint();++ if (running) {+ child?.postMessage({ type: "deleteProject", projectId });+ }}/** Asks the host to stop (it kills its harness trees), then kills it after a grace period. */diff --git a/apps/desktop/src/dapi/handler.ts b/apps/desktop/src/dapi/handler.tsindex f7a32294..4b9b31b2 100644--- a/apps/desktop/src/dapi/handler.ts+++ b/apps/desktop/src/dapi/handler.ts@@ -4,6 +4,16 @@import type { LogEntry, ToolArgs, ToolResult } from "@diffusionstudio/dapi";+/** The main window, as the `window` tool drives it. */+export type AppWindow = {+ /** Whether the window is out for the user. */+ visible(): boolean;+ /** Shows and focuses it, creating it when there is none. */+ show(): Promise<void>;+ /** Puts it away; the app keeps running in the background. */+ hide(): void;+};+/** What a main-process handler gets besides its arguments. */export type MainContext = {/** Fires when the caller cancels or goes away. */@@ -12,10 +22,12 @@ export type MainContext = {logs(): LogEntry[];/** The app's version. */version: string;+ /** The main window. */+ window: AppWindow;};-/** The tools that need the file system or a child process, not a window. */-export type MainToolName = "logs" | "report";+/** The tools that need the file system, a child process or the window itself, not a renderer. */+export type MainToolName = "logs" | "report" | "window";export type MainHandler<N extends MainToolName> = (args: ToolArgs<N>, ctx: MainContext) => Promise<ToolResult<N>>;diff --git a/apps/desktop/src/dapi/handlers/index.ts b/apps/desktop/src/dapi/handlers/index.tsindex b34ad023..39d2e648 100644--- a/apps/desktop/src/dapi/handlers/index.ts+++ b/apps/desktop/src/dapi/handlers/index.ts@@ -4,8 +4,9 @@import { logs } from "./logs";import { report } from "./report";+import { window } from "./window";import type { MainHandlers } from "../handler";/** Every tool main answers itself, keyed by its catalog name. */-export const mainHandlers: MainHandlers = { logs, report };+export const mainHandlers: MainHandlers = { logs, report, window };diff --git a/apps/desktop/src/dapi/handlers/logs.test.ts b/apps/desktop/src/dapi/handlers/logs.test.tsindex d8496feb..7bb25c77 100644--- a/apps/desktop/src/dapi/handlers/logs.test.ts+++ b/apps/desktop/src/dapi/handlers/logs.test.ts@@ -11,7 +11,8 @@ import type { MainContext } from "../handler";const entry = (ts: number, message: string, level: LogEntry["level"] = "info"): LogEntry => ({ ts, level, message, source: "" });-const ctx = (entries: LogEntry[]): MainContext => ({ signal: new AbortController().signal, logs: () => entries, version: "0" });+const noWindow = { visible: () => false, show: async () => {}, hide: () => {} };+const ctx = (entries: LogEntry[]): MainContext => ({ signal: new AbortController().signal, logs: () => entries, version: "0", window: noWindow });describe("logs", () => {it("returns the last LOG_TAIL entries when no tail is given", async () => {diff --git a/apps/desktop/src/dapi/handlers/window.ts b/apps/desktop/src/dapi/handlers/window.tsnew file mode 100644index 00000000..76627a07--- /dev/null+++ b/apps/desktop/src/dapi/handlers/window.ts@@ -0,0 +1,15 @@+/* 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 type { MainHandler } from "../handler";++export const window: MainHandler<"window"> = async ({ visible }, ctx) => {+ if (visible === true) {+ await ctx.window.show();+ } else if (visible === false) {+ ctx.window.hide();+ }++ return { visible: ctx.window.visible() };+};diff --git a/apps/desktop/src/dapi/http.test.ts b/apps/desktop/src/dapi/http.test.tsindex 2bd6a6c8..5a91bd4d 100644--- a/apps/desktop/src/dapi/http.test.ts+++ b/apps/desktop/src/dapi/http.test.ts@@ -14,7 +14,6 @@ import { DapiHttpServer } from "./http";const PORT = 3200 + Math.floor(Math.random() * 500);const PATH = "/mcp";let server: DapiHttpServer;-let firstConnections = 0;let sessionsCreated = 0;beforeAll(async () => {@@ -22,7 +21,6 @@ beforeAll(async () => {host: "127.0.0.1",port: PORT,path: PATH,- onFirstConnection: () => void firstConnections++,createSession() {sessionsCreated++;const session = new McpServer({ name: "test", version: "0.0.0" }, { instructions: "Test instructions." });@@ -60,12 +58,11 @@ describe("mcp over http", () => {await client.close();});- it("gives each client its own session and reports the first once", async () => {+ it("gives each client its own session", async () => {const before = sessionsCreated;const a = await connect();const b = await connect();expect(sessionsCreated - before).toBe(2);- expect(firstConnections).toBe(1);await a.close();await b.close();});diff --git a/apps/desktop/src/dapi/http.ts b/apps/desktop/src/dapi/http.tsindex a9e7a725..0ce8f5f6 100644--- a/apps/desktop/src/dapi/http.ts+++ b/apps/desktop/src/dapi/http.ts@@ -23,16 +23,8 @@ export type HttpServerDeps = {path: string;/** A fresh MCP server with the tools and resources registered, one per session. */createSession(): McpServer;- /**- * Called once, when the first session initializes — unless that session- * says `?client=chat` in its URL: the in-app chat is watched by the user,- * so it must not switch the app into remote-controlled mode.- */- onFirstConnection(): void;};-const CHAT_CLIENT = "chat";-type Session = { transport: StreamableHTTPServerTransport; server: McpServer };const SESSION_HEADER = "mcp-session-id";@@ -41,7 +33,6 @@ export class DapiHttpServer {private readonly deps: HttpServerDeps;private readonly sessions = new Map<string, Session>();private server: Server | null = null;- private connected = false;constructor(deps: HttpServerDeps) {this.deps = deps;@@ -98,14 +89,14 @@ export class DapiHttpServer {}// No session: either an `initialize`, which the transport answers with// a new id, or a stray request it rejects with 400.- await this.open(url.searchParams.get("client")).transport.handleRequest(req, res);+ await this.open().transport.handleRequest(req, res);} catch (error) {console.error("[dapi] http request failed:", error);if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" }).end("Internal error");}}- private open(client: string | null): Session {+ private open(): Session {const server = this.deps.createSession();const hosts = [this.deps.host, "localhost"];const transport = new StreamableHTTPServerTransport({@@ -114,10 +105,6 @@ export class DapiHttpServer {allowedHosts: [...hosts, ...hosts.map((host) => `${host}:${this.deps.port}`)],onsessioninitialized: (id) => {this.sessions.set(id, session);- if (!this.connected && client !== CHAT_CLIENT) {- this.connected = true;- this.deps.onFirstConnection();- }},onsessionclosed: (id) => {this.sessions.delete(id);diff --git a/apps/desktop/src/dapi/renderer-calls.ts b/apps/desktop/src/dapi/renderer-calls.tsindex e5be4f51..eddae6d9 100644--- a/apps/desktop/src/dapi/renderer-calls.ts+++ b/apps/desktop/src/dapi/renderer-calls.ts@@ -3,9 +3,10 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { randomUUID } from "node:crypto";-import { app, BrowserWindow, ipcMain } from "electron";+import { ipcMain } from "electron";import { DAPI_WIRE, DapiError } from "@diffusionstudio/dapi";+import type { BrowserWindow } from "electron";import type { DapiCall, DapiCancel, DapiReply } from "@diffusionstudio/dapi";type InFlight = {@@ -13,15 +14,33 @@ type InFlight = {reject(error: Error): void;};+/** Where renderer calls find their window. */+export type RendererHost = {+ /** The main window, created hidden when there is none; `fresh` when this call created it. */+ acquire(): { window: BrowserWindow; fresh: boolean };+ /** The project the editor last had open, to reopen in a window created for a call. */+ lastProject(): string | null;+};+/*** Runs renderer tools from main: one `dapi:call` per request, answered by- * `dapi:reply`, or `dapi:cancel` if the caller gives up. Calls wait for the- * current window to finish loading; a window that reloads or dies fails the- * calls it was answering.+ * `dapi:reply`, or `dapi:cancel` if the caller gives up. There may be no+ * window when a call arrives — it is only kept while something needs it — so+ * a call creates one, and waits for it to load and to reopen the project the+ * agent was working on. A window that reloads or dies fails the calls it was+ * answering.*/export class RendererCalls {+ private readonly host: RendererHost;private readonly inFlight = new Map<string, InFlight>();- private window: BrowserWindow | null = null;+ private readonly tracked = new WeakSet<BrowserWindow>();+ // Settles once the current window has loaded, and reopened the project+ // when it was created for a call. Every call waits on it.+ private ready: Promise<BrowserWindow> | null = null;++ constructor(host: RendererHost) {+ this.host = host;+ }start(): void {ipcMain.on(DAPI_WIRE.REPLY, (_event, reply: DapiReply) => {@@ -31,14 +50,47 @@ export class RendererCalls {if (reply.ok) call.resolve(reply.data);else call.reject(reply.error.code ? new DapiError(reply.error.code, reply.error.message) : new Error(reply.error.message));});-- app.on("browser-window-created", (_event, window) => this.track(window));- const windows = BrowserWindow.getAllWindows();- if (windows.length > 0) this.track(windows[windows.length - 1]!);}async call(tool: string, args: unknown, signal: AbortSignal): Promise<unknown> {- const window = await this.ready();+ const window = await this.window(tool);+ if (window.isDestroyed()) {+ throw new Error("The app window closed before replying");+ }+ return this.send(window, tool, args, signal);+ }++ // The window to answer on. One created here is tracked, and gets the last+ // project reopened — unless the call is itself an `open` — since the calls+ // that follow assume the project the agent opened is still open. A project+ // that no longer opens is left to the call to report.+ private window(tool: string): Promise<BrowserWindow> {+ const { window, fresh } = this.host.acquire();+ // Loaded before, but it may have reloaded since.+ if (!fresh && this.ready) {+ return this.ready.then(loaded);+ }++ this.track(window);+ const dir = fresh && tool !== "open" ? this.host.lastProject() : null;+ const ready = loaded(window).then(async (loadedWindow) => {+ if (dir) {+ await this.send(loadedWindow, "open", { dir }, new AbortController().signal).catch((error: Error) =>+ console.warn(`[dapi] could not reopen ${dir}: ${error.message}`),+ );+ }+ return loadedWindow;+ });+ this.ready = ready;+ // A window that failed to load is not waited on again: the next call+ // finds out afresh.+ ready.catch(() => {+ if (this.ready === ready) this.ready = null;+ });+ return ready;+ }++ private send(window: BrowserWindow, tool: string, args: unknown, signal: AbortSignal): Promise<unknown> {const id = randomUUID();return new Promise((resolve, reject) => {const onAbort = () => {@@ -62,12 +114,13 @@ export class RendererCalls {}private track(window: BrowserWindow): void {- this.window = window;+ if (this.tracked.has(window)) return;+ this.tracked.add(window);const fail = (why: string) => () => this.failAll(why);window.webContents.on("did-start-loading", fail("The app reloaded before replying"));window.webContents.on("render-process-gone", fail("The app's renderer crashed"));window.on("closed", () => {- if (this.window === window) this.window = null;+ this.ready = null;this.failAll("The app window closed before replying");});}@@ -78,33 +131,33 @@ export class RendererCalls {for (const call of calls) call.reject(new Error(message));}- // Resolves with the current window once it has finished loading.- private ready(timeoutMs = 30000): Promise<BrowserWindow> {- const window = this.window;- if (!window || window.isDestroyed()) return Promise.reject(new Error("The app has no window"));- if (window.webContents.isCrashed()) return Promise.reject(new Error("The app's renderer crashed"));- if (!window.webContents.isLoading()) return Promise.resolve(window);+}- return new Promise((resolve, reject) => {- const timer = setTimeout(() => {- cleanup();- reject(new Error("The app did not become ready in time"));- }, timeoutMs);- const cleanup = () => {- clearTimeout(timer);- window.webContents.off("did-finish-load", onLoad);- window.webContents.off("did-fail-load", onFail);- };- const onLoad = () => {- cleanup();- resolve(window);- };- const onFail = () => {- cleanup();- reject(new Error("The app failed to load"));- };- window.webContents.on("did-finish-load", onLoad);- window.webContents.on("did-fail-load", onFail);- });- }+// Resolves with the window once it has finished loading.+function loaded(window: BrowserWindow, timeoutMs = 30000): Promise<BrowserWindow> {+ if (window.isDestroyed()) return Promise.reject(new Error("The app has no window"));+ if (window.webContents.isCrashed()) return Promise.reject(new Error("The app's renderer crashed"));+ if (!window.webContents.isLoading()) return Promise.resolve(window);++ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ cleanup();+ reject(new Error("The app did not become ready in time"));+ }, timeoutMs);+ const cleanup = () => {+ clearTimeout(timer);+ window.webContents.off("did-finish-load", onLoad);+ window.webContents.off("did-fail-load", onFail);+ };+ const onLoad = () => {+ cleanup();+ resolve(window);+ };+ const onFail = () => {+ cleanup();+ reject(new Error("The app failed to load"));+ };+ window.webContents.on("did-finish-load", onLoad);+ window.webContents.on("did-fail-load", onFail);+ });}diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.tsindex a434504f..5b0bef1b 100644--- a/apps/desktop/src/dapi/server.ts+++ b/apps/desktop/src/dapi/server.ts@@ -11,7 +11,8 @@ import { RendererCalls } from "./renderer-calls";import { serveCatalog } from "./tools-session";import type { LogEntry } from "@diffusionstudio/dapi";-import type { MainContext, MainToolName } from "./handler";+import type { AppWindow, MainContext, MainToolName } from "./handler";+import type { RendererHost } from "./renderer-calls";/*** The name the server introduces itself with, and so the namespace an agent@@ -25,8 +26,11 @@ export type DapiServerDeps = {version: string;/** The app's console buffer, for `logs` and `report`. */logs(): LogEntry[];- /** Called once, on the first connection: an agent is driving, so the UI may step back. */- onFirstConnection(): void;+ /** The main window: where renderer tools run, and what `window` shows and hides. */+ window: AppWindow & RendererHost & {+ /** Keeps the window from idling out while a call runs; returns the release. */+ hold(): () => void;+ };/** The staged docs: INSTRUCTIONS.md, their path, and the skill headers, all for every session. Null when not staged. */docsDir: string | null;};@@ -40,13 +44,14 @@ export type DapiServerDeps = {*/export class DapiServer {private readonly deps: DapiServerDeps;- private readonly renderer = new RendererCalls();+ private readonly renderer: RendererCalls;private readonly http: DapiHttpServer;private instructionsText: string | null = null;private httpReady: Promise<boolean> = Promise.resolve(false);constructor(deps: DapiServerDeps) {this.deps = deps;+ this.renderer = new RendererCalls(deps.window);for (const tool of tools) {if (tool.environment === "main" && !(tool.name in mainHandlers)) {throw new Error(`Main-process tool "${tool.name}" has no handler`);@@ -57,7 +62,6 @@ export class DapiServer {port: MCP_PORT,path: MCP_PATH,createSession: () => this.createSession(),- onFirstConnection: () => deps.onFirstConnection(),});}@@ -94,16 +98,21 @@ export class DapiServer {// `name` is the machine identity, and matches the key we write into agent// configs; `title` is what a client shows a person.const session = new McpServer({ name: SERVER_NAME, title: "Diffusion Studio", version: this.deps.version }, { instructions: this.instructionsText });- serveCatalog(session, (tool, args, signal) =>- tool.environment === "main" ?- this.runInMain(tool.name as MainToolName, args, signal)- : this.renderer.call(tool.name, args, signal),- );+ serveCatalog(session, async (tool, args, signal) => {+ const release = this.deps.window.hold();+ try {+ return await (tool.environment === "main" ?+ this.runInMain(tool.name as MainToolName, args, signal)+ : this.renderer.call(tool.name, args, signal));+ } finally {+ release();+ }+ });return session;}private runInMain(name: MainToolName, args: unknown, signal: AbortSignal): Promise<unknown> {- const ctx: MainContext = { signal, logs: this.deps.logs, version: this.deps.version };+ const ctx: MainContext = { signal, logs: this.deps.logs, version: this.deps.version, window: this.deps.window };// Each handler takes its own parsed args; the map's union type cannot// express that pairing, so the call site widens.return (mainHandlers[name] as (args: unknown, ctx: MainContext) => Promise<unknown>)(args, ctx);diff --git a/apps/desktop/src/headless.ts b/apps/desktop/src/headless.tsdeleted file mode 100644index b695807e..00000000--- a/apps/desktop/src/headless.ts+++ /dev/null@@ -1,18 +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/. */--// Whether an agent has connected since launch. Once one has, the UI steps-// back: file writes from tools are not echoed as edits, and the window may-// stay hidden. Set by the MCP server on its first connection; read wherever-// behaviour depends on who is driving.--let headless = false;--export function isHeadless(): boolean {- return headless;-}--export function enableHeadless(): void {- headless = true;-}diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 60a8e2b3..e6d2db59 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -36,6 +36,7 @@ export const MAIN_CHANNELS = {WINDOW_IS_FULLSCREEN: "window:is-fullscreen",WINDOW_SET_COLOR_MODE: "window:set-color-mode",WINDOW_CAPTURE: "window:capture",+ WINDOW_SET_BUSY: "window:set-busy",FILE_TRANSFER: "file:transfer",FILE_WRITE_OPEN: "file:write-open",FILE_WRITE_CHUNK: "file:write-chunk",@@ -192,6 +193,7 @@ export type MainRequestMap = {[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.WINDOW_SET_BUSY]: { request: { busy: boolean }; response: void };[MAIN_CHANNELS.FILE_TRANSFER]: {request: { selector: string; absolutePath: string };response: void;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 8dcad13c..25b86e4d 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -8,15 +8,16 @@ import { existsSync } from "node:fs";import { mkdir, open, rename, unlink } from "node:fs/promises";import { randomUUID } from "node:crypto";import type { FileHandle } from "node:fs/promises";-import { updateElectronApp } from "update-electron-app";+import { makeUserNotifier, updateElectronApp } from "update-electron-app";import { tempPathFor } from "./atomic";import { DapiServer } from "./dapi/server";-import { agentChatEndpoint, deleteProjectChats, startAgentChat, stopAgentChat } from "./agent-chat";+import { agentChatEndpoint, configureAgentChat, deleteProjectChats, stopAgentChat } from "./agent-chat";import { cliStatus, installCli, refreshCliShim, uninstallCli } from "./cli-install";import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";-import { enableHeadless } from "./headless";import { trackEvent, trackInstall } from "./analytics";import { setupAppMenu } from "./menu";+import { AppTray } from "./tray";+import { WindowHost } from "./window-host";import { handleSquirrelEvent } from "./squirrel";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";@@ -52,6 +53,7 @@ import type { DeepLinkChannel } from "./main-channels";import type { LogEntry } from "@diffusionstudio/dapi";const DEV_URL = "http://localhost:5173";+const WINDOW_IDLE_MS = 10 * 60 * 1000;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 };@@ -105,13 +107,36 @@ function setColorMode(mode: "dark" | "light") {mainWindow.setTitleBarOverlay({ ...WINDOWS_OVERLAY_COLORS[mode], height: WINDOWS_OVERLAY_HEIGHT });}-if (app.isPackaged && !squirrelLaunch && !process.argv.includes("--hidden")) {- updateElectronApp({ repo: "diffusionstudio/editor" });+if (app.isPackaged && !squirrelLaunch) {+ const notifyUser = makeUserNotifier();+ updateElectronApp({+ repo: "diffusionstudio/editor",+ onNotifyUser: function (info) {+ if (windows.visible()) {+ notifyUser(info);+ }+ },+ });}const openWrites = new Map<string, { handle: FileHandle; path: string; temp: string; reserved: boolean }>();let mainWindow: BrowserWindow | null = null;+let lastProject: string | null = null;++const windows = new WindowHost({+ create: createWindow,+ idleMs: WINDOW_IDLE_MS,+ onChange: () => tray.refresh(),+});++const tray = new AppTray({+ visible: () => windows.visible(),+ active: () => windows.active(),+ project: () => lastProject,+ show: () => void windows.show(),+ hide: () => windows.hide(),+});// Deep links that arrived before the renderer could take them, keyed by the// channel they belong to so auth and checkout never drain each other's link.@@ -133,12 +158,19 @@ function docsDir(): string | null {}// The MCP server agents and the diffusion CLI talk to. Started once the app is-// ready; the first connection switches the app into headless mode.+// ready; renderer tools create the window when there is none.const dapi = new DapiServer({version: app.getVersion(),logs: () => logBuffer,docsDir: docsDir(),- onFirstConnection: enableHeadless,+ window: {+ visible: () => windows.visible(),+ show: () => windows.show(),+ hide: () => windows.hide(),+ acquire: () => windows.acquire(),+ hold: () => windows.hold(),+ lastProject: () => lastProject,+ },});function pushLog(level: LogEntry["level"], message: string, source: string) {@@ -220,7 +252,8 @@ async function setFileInputFiles(selector: string, absolutePath: string) {});}-function createWindow(show = true) {+// The main window, not shown: WindowHost decides when it is.+function createWindow(): BrowserWindow {const options: Electron.BrowserWindowConstructorOptions = {show: false,@@ -260,10 +293,6 @@ function createWindow(show = true) {mainWindow.once("ready-to-show", () => {applyCornerRadius(MACOS_CORNER_RADIUS);applyBackdrop();-- if (show) {- mainWindow?.show();- }});mainWindow.on("show", () => {@@ -281,6 +310,7 @@ function createWindow(show = true) {});mainWindow.on("closed", () => {mainWindow = null;+ unwatchAll();});if (!app.isPackaged) {@@ -288,6 +318,8 @@ function createWindow(show = true) {} else {mainWindow.loadFile(join(app.getAppPath(), "web", "index.html"));}++ return mainWindow;}if (process.defaultApp && process.argv.length >= 2) {@@ -301,24 +333,24 @@ if (process.defaultApp && process.argv.length >= 2) {if (squirrelLaunch) {// Update.exe is at work; handleSquirrelEvent quits the app when it is done.} else if (app.requestSingleInstanceLock()) {+ if (isHiddenLaunch(process.argv)) {+ app.dock?.hide();+ }+app.on("second-instance", (_event, argv) => {const url = findProtocolUrl(argv);- if (url) deliverDeepLink(url);-- const hidden = isHiddenLaunch(argv);- if (mainWindow && !mainWindow.isDestroyed()) {- if (hidden) return;- if (mainWindow.isMinimized()) mainWindow.restore();- mainWindow.show();- mainWindow.focus();- } else {- createWindow(!hidden);+ if (url) {+ deliverDeepLink(url);+ }+ if (!isHiddenLaunch(argv)) {+ windows.show();}});app.on("open-url", (event, url) => {event.preventDefault();deliverDeepLink(url);+ windows.show();});mainBridge.handle(MAIN_CHANNELS.APP_OPEN_EXTERNAL, ({ url }) => shell.openExternal(url));@@ -332,6 +364,7 @@ if (squirrelLaunch) {);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_SET_BUSY, ({ busy }) => windows.setBusy(busy));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 });@@ -362,10 +395,18 @@ if (squirrelLaunch) {mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir).then(deleteProjectChats));mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => writeProject(dir, edits));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) =>- watchProject(BrowserWindow.fromWebContents(event.sender), dir),- );- mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => unwatchProject(dir));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) => {+ lastProject = dir;+ tray.refresh();+ watchProject(BrowserWindow.fromWebContents(event.sender), dir);+ });+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => {+ if (lastProject === dir) {+ lastProject = null;+ tray.refresh();+ }+ unwatchProject(dir);+ });mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_READ, ({ dir }) => readManifest(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE, ({ dir, manifest }) => writeManifest(dir, manifest));mainBridge.handle(MAIN_CHANNELS.PROJECTS_CONFIG_READ, ({ dir }) => readConfig(dir));@@ -455,45 +496,38 @@ if (squirrelLaunch) {if (url) deliverDeepLink(url);dapi.start();- // The chat's sessions get the MCP server by URL; `?client=chat` keeps the- // app from switching into remote-controlled mode for them (see dapi/http).+ // The chat's sessions get the MCP server by URL.dapi.mcpUrl().then((url) =>- startAgentChat({+ configureAgentChat({dataDir: join(app.getPath("userData"), "agent-chat"),- mcpUrl: url ? `${url}?client=chat` : null,+ mcpUrl: url,version: app.getVersion(),}),);refreshCliShim();healMcpRegistrations();trackInstall();- createWindow(!isHiddenLaunch(process.argv));+ tray.start();++ // Opened by a person (Finder, Dock, Start menu): show the editor+ if (!isHiddenLaunch(process.argv)) {+ windows.show();+ }});app.on("before-quit", () => {unwatchAll();stopAgentChat();dapi.stop();+ tray.destroy();});- app.on("window-all-closed", () => {- if (process.platform !== "darwin") {- app.quit();- }- });+ // No window is no reason to quit: the app keeps serving agents from the+ // tray, and the window is destroyed whenever it idles out. Only Quit ends it.+ app.on("window-all-closed", () => { });- app.on("activate", () => {- if (!mainWindow || mainWindow.isDestroyed()) {- createWindow();- return;- }-- if (mainWindow.isMinimized()) {- mainWindow.restore();- }- mainWindow.show();- mainWindow.focus();- });+ // The Dock icon, or launching the app again while it runs.+ app.on("activate", () => windows.show());} else {app.quit();}diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 24c27ecc..f603f095 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -18,7 +18,6 @@ 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";import { applyEdits, editLabel, stampProject } from "./edit";@@ -344,8 +343,8 @@ export async function cloudSyncKind(path: string): Promise<string | null> {/*** Whether to go ahead with `path`: true when nothing syncs it, and when the* user has been told what syncing does to a project and wants it anyway.- * Headless runs are never asked — there is nobody to ask — and proceed with- * the warning in the log.+ * Nobody is asked while the window is hidden — an agent is driving and there+ * is nobody to ask — and the project goes ahead with the warning in the log.*/async function confirmCloudLocation(window: BrowserWindow | null,@@ -355,7 +354,7 @@ async function confirmCloudLocation(const kind = await cloudSyncKind(path);if (!kind) return true;- if (isHeadless()) {+ if (!window?.isVisible()) {console.warn(`[projects] ${path} is synced by ${kind}; projects there may misbehave`);return true;}diff --git a/apps/desktop/src/tray.ts b/apps/desktop/src/tray.tsnew file mode 100644index 00000000..91207003--- /dev/null+++ b/apps/desktop/src/tray.ts@@ -0,0 +1,131 @@+/* 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 app's one permanent presence: agents use the app in the background, so+// the menu bar (macOS) or notification area (Windows) is where it shows that+// it is running, that an agent is working in it, and where the user opens+// the editor or quits.++import { basename } from "node:path";+import { app, Menu, nativeImage, Tray } from "electron";++import idle1x from "../assets/tray/idleTemplate.png";+import idle2x from "../assets/tray/[email protected]";+import busy1x from "../assets/tray/busyTemplate.png";+import busy2x from "../assets/tray/[email protected]";+import win1x from "../assets/tray/win.png";+import win2x from "../assets/tray/[email protected]";++import type { NativeImage } from "electron";++export type AppTrayDeps = {+ /** Whether the window is out for the user. */+ visible(): boolean;+ /** Whether a tool call is running. */+ active(): boolean;+ /** The project the editor last had open. */+ project(): string | null;+ show(): void;+ hide(): void;+};++// Calls come in bursts of short ones; the icon stays busy this long after the+// last so it does not flicker between them.+const BUSY_LINGER = 1500;++function image(x1: Uint8Array, x2: Uint8Array, template: boolean): NativeImage {+ const icon = nativeImage.createFromBuffer(Buffer.from(x1), { scaleFactor: 1 });+ icon.addRepresentation({ scaleFactor: 2, buffer: Buffer.from(x2) });+ icon.setTemplateImage(template);+ return icon;+}++export class AppTray {+ private readonly deps: AppTrayDeps;+ private tray: Tray | null = null;+ private idleIcon: NativeImage | null = null;+ private busyIcon: NativeImage | null = null;+ private busy = false;+ private lingerTimer: NodeJS.Timeout | null = null;+ private wasVisible = false;+ private toldStillRunning = false;++ constructor(deps: AppTrayDeps) {+ this.deps = deps;+ }++ /** Puts the icon up; call once the app is ready. */+ start(): void {+ if (process.platform === "darwin") {+ // Template images: macOS tints them to fit the menu bar.+ this.idleIcon = image(idle1x, idle2x, true);+ this.busyIcon = image(busy1x, busy2x, true);+ } else {+ this.idleIcon = this.busyIcon = image(win1x, win2x, false);+ }+ this.tray = new Tray(this.idleIcon);+ // macOS opens the menu on click; elsewhere the menu is the right click+ // and a click opens the editor.+ if (process.platform !== "darwin") this.tray.on("click", () => this.deps.show());+ this.refresh();+ }++ /** Brings the icon and menu up to date; call whenever what they show changes. */+ refresh(): void {+ const tray = this.tray;+ if (!tray) return;++ this.updateBusy();+ const visible = this.deps.visible();+ const project = this.deps.project();+ const status = this.busy ? "An agent is working…" : "Ready for agents";++ tray.setImage(this.busy ? this.busyIcon! : this.idleIcon!);+ tray.setToolTip(`${app.name} — ${status}`);+ tray.setContextMenu(+ Menu.buildFromTemplate([+ visible ?+ { label: `Hide ${app.name}`, click: () => this.deps.hide() }+ : { label: `Open ${app.name}`, click: () => this.deps.show() },+ { type: "separator" },+ { label: status, enabled: false },+ ...(project ? [{ label: `Project: ${basename(project)}`, enabled: false }] : []),+ { type: "separator" },+ { label: `Quit ${app.name}`, click: () => app.quit() },+ ]),+ );++ // Windows has no Dock to hint that closing the window did not quit; say+ // so once, the first time it goes away.+ if (process.platform === "win32" && this.wasVisible && !visible && !this.toldStillRunning) {+ this.toldStillRunning = true;+ tray.displayBalloon({+ iconType: "info",+ title: `${app.name} is still running`,+ content: "Agents can keep using it in the background. Open it again from here.",+ });+ }+ this.wasVisible = visible;+ }++ destroy(): void {+ if (this.lingerTimer) clearTimeout(this.lingerTimer);+ this.tray?.destroy();+ this.tray = null;+ }++ private updateBusy(): void {+ if (this.deps.active()) {+ if (this.lingerTimer) clearTimeout(this.lingerTimer);+ this.lingerTimer = null;+ this.busy = true;+ } else if (this.busy && !this.lingerTimer) {+ this.lingerTimer = setTimeout(() => {+ this.lingerTimer = null;+ this.busy = false;+ this.refresh();+ }, BUSY_LINGER);+ }+ }+}diff --git a/apps/desktop/src/untyped-modules.d.ts b/apps/desktop/src/untyped-modules.d.tsindex 736500ea..d6115759 100644--- a/apps/desktop/src/untyped-modules.d.ts+++ b/apps/desktop/src/untyped-modules.d.ts@@ -13,3 +13,10 @@ declare module "@babel/preset-typescript" {const preset: unknown;export default preset;}++// The tray icons, bundled into main.js as bytes (`--loader:.png=binary`):+// the packaged app ships dist/ and web/ only.+declare module "*.png" {+ const bytes: Uint8Array;+ export default bytes;+}diff --git a/apps/desktop/src/window-host.test.ts b/apps/desktop/src/window-host.test.tsnew file mode 100644index 00000000..c2ff5f94--- /dev/null+++ b/apps/desktop/src/window-host.test.ts@@ -0,0 +1,135 @@+/* 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 { EventEmitter } from "node:events";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const appEvents = new EventEmitter();+const dock = { show: vi.fn(async () => { }), hide: vi.fn() };++vi.mock("electron", () => ({+ app: { on: (event: string, listener: () => void) => appEvents.on(event, listener), dock, focus: () => { } },+}));++const { WindowHost } = await import("./window-host");++/** Just enough of a BrowserWindow: visibility, close and destroy. */+class FakeWindow extends EventEmitter {+ destroyed = false;+ isVisibleNow = false;+ isDestroyed = () => this.destroyed;+ isVisible = () => this.isVisibleNow;+ isFullScreen = () => false;+ isMinimized = () => false;+ show = () => void (this.isVisibleNow = true);+ hide = () => void (this.isVisibleNow = false);+ focus = () => { };+ restore = () => { };+ close(): void {+ const event = { defaultPrevented: false, preventDefault: () => void (event.defaultPrevented = true) };+ this.emit("close", event);+ if (!event.defaultPrevented) this.destroy();+ }+ destroy(): void {+ if (this.destroyed) return;+ this.destroyed = true;+ this.emit("closed");+ }+}++const IDLE = 60_000;+let created: FakeWindow[];+let host: InstanceType<typeof WindowHost>;++beforeEach(() => {+ vi.useFakeTimers();+ appEvents.removeAllListeners();+ created = [];+ host = new WindowHost({+ create: () => {+ const window = new FakeWindow();+ created.push(window);+ // Painted right away, so `show` does not wait.+ queueMicrotask(() => window.emit("ready-to-show"));+ return window as never;+ },+ idleMs: IDLE,+ onChange: () => { },+ });+});++afterEach(() => {+ vi.useRealTimers();+});++describe("WindowHost", () => {+ it("creates the window only when something needs it, and reuses it", () => {+ expect(host.current()).toBeNull();+ expect(host.acquire().fresh).toBe(true);+ expect(host.acquire().fresh).toBe(false);+ expect(created).toHaveLength(1);+ expect(host.visible()).toBe(false);+ });++ it("destroys a hidden window once it has sat unused for the idle time", () => {+ host.acquire();+ vi.advanceTimersByTime(IDLE - 1);+ expect(host.current()).not.toBeNull();+ vi.advanceTimersByTime(1);+ expect(host.current()).toBeNull();+ expect(host.acquire().fresh).toBe(true);+ });++ it("keeps the window while a call holds it, and counts idle time from the release", () => {+ host.acquire();+ const release = host.hold();+ expect(host.active()).toBe(true);+ vi.advanceTimersByTime(IDLE * 2);+ expect(host.current()).not.toBeNull();+ release();+ release();+ expect(host.active()).toBe(false);+ vi.advanceTimersByTime(IDLE - 1);+ expect(host.current()).not.toBeNull();+ vi.advanceTimersByTime(1);+ expect(host.current()).toBeNull();+ });++ it("keeps the window while the renderer reports work of its own", () => {+ host.acquire();+ host.setBusy(true);+ vi.advanceTimersByTime(IDLE * 2);+ expect(host.current()).not.toBeNull();+ host.setBusy(false);+ vi.advanceTimersByTime(IDLE);+ expect(host.current()).toBeNull();+ });++ it("never idles out a window the user has open, and gives the app a Dock icon while it is", async () => {+ await host.show();+ expect(host.visible()).toBe(true);+ expect(dock.show).toHaveBeenCalled();+ vi.advanceTimersByTime(IDLE * 2);+ expect(host.current()).not.toBeNull();+ });++ it("hides the window when the user closes it, and idles it out from there", async () => {+ await host.show();+ const window = created[0]!;+ window.close();+ expect(window.isDestroyed()).toBe(false);+ expect(host.visible()).toBe(false);+ expect(dock.hide).toHaveBeenCalled();+ vi.advanceTimersByTime(IDLE);+ expect(window.isDestroyed()).toBe(true);+ });++ it("lets the window close when the app quits", async () => {+ await host.show();+ appEvents.emit("before-quit");+ created[0]!.close();+ expect(created[0]!.isDestroyed()).toBe(true);+ expect(host.current()).toBeNull();+ });+});diff --git a/apps/desktop/src/window-host.ts b/apps/desktop/src/window-host.tsnew file mode 100644index 00000000..8ad66241--- /dev/null+++ b/apps/desktop/src/window-host.ts@@ -0,0 +1,172 @@+/* 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 main window's lifecycle. The app runs in the background while agents+// use it — a tray icon, no Dock icon, no window — and the window, and with it+// the renderer that answers most tools, only exists while something needs+// it: a tool call, or the user. Hidden and unused for long enough, it is torn+// down again, and the app is back to its main process alone.+//+// Everything that shows, hides or needs the window comes through here, so+// the Dock icon (macOS) follows whether the window is showing, and closing+// the window hides it rather than ending what the renderer is doing.++import { app } from "electron";++import type { BrowserWindow } from "electron";++export type WindowHostDeps = {+ /** A new main window, not shown; loading starts right away. */+ create(): BrowserWindow;+ /** How long a hidden window may sit unused before it is destroyed. */+ idleMs: number;+ /** Whether the window is showing, or whether calls are running, changed. */+ onChange(): void;+};++/** Longest a first show waits for the page to paint before showing it anyway. */+const FIRST_PAINT_TIMEOUT = 5000;++export class WindowHost {+ private readonly deps: WindowHostDeps;+ private window: BrowserWindow | null = null;+ private painted: Promise<void> = Promise.resolve();+ // Whether the user should be seeing the window: set by `show`, cleared by+ // `hide`. Not `isVisible()`, which a minimize or ⌘H also clears — neither+ // of those is the user putting the window away, so neither lets it idle+ // out or takes the Dock icon.+ private shown = false;+ private holds = 0;+ private busy = false;+ private idleTimer: NodeJS.Timeout | null = null;+ private quitting = false;++ constructor(deps: WindowHostDeps) {+ this.deps = deps;+ app.on("before-quit", () => {+ this.quitting = true;+ });+ }++ /** The window, if there is one. */+ current(): BrowserWindow | null {+ return this.window && !this.window.isDestroyed() ? this.window : null;+ }++ /** Whether the window is out for the user (minimized counts). */+ visible(): boolean {+ return this.shown && this.current() !== null;+ }++ /** Whether any call is holding the window. */+ active(): boolean {+ return this.holds > 0;+ }++ /** The window, created hidden when there is none; `fresh` when this call created it. */+ acquire(): { window: BrowserWindow; fresh: boolean } {+ const existing = this.current();+ if (existing) return { window: existing, fresh: false };++ const window = this.deps.create();+ this.window = window;+ this.painted = new Promise((resolve) => {+ window.once("ready-to-show", () => resolve());+ setTimeout(resolve, FIRST_PAINT_TIMEOUT);+ });++ // Closing puts the window away; only quitting ends it (and idling out,+ // which destroys it without a `close`).+ window.on("close", (event) => {+ if (this.quitting) return;+ event.preventDefault();+ this.hide();+ });+ window.on("closed", () => {+ if (this.window !== window) return;+ this.window = null;+ this.shown = false;+ this.busy = false;+ this.clearIdle();+ this.deps.onChange();+ });++ this.scheduleIdle();+ return { window, fresh: true };+ }++ /** Shows and focuses the window, creating it when there is none. */+ async show(): Promise<void> {+ const { window } = this.acquire();+ this.shown = true;+ this.clearIdle();+ // Before the window: shown by an app without a Dock icon, it would not+ // come to the front.+ if (process.platform === "darwin") await app.dock?.show();+ await this.painted;+ if (window.isDestroyed()) return;+ if (window.isMinimized()) window.restore();+ window.show();+ window.focus();+ if (process.platform === "darwin") app.focus({ steal: true });+ this.deps.onChange();+ }++ /** Puts the window away. It stays loaded until it idles out. */+ hide(): void {+ const window = this.current();+ if (!window) return;+ // Hiding a full-screen window leaves its empty Space behind.+ if (window.isFullScreen()) {+ window.once("leave-full-screen", () => this.hide());+ window.setFullScreen(false);+ return;+ }+ this.shown = false;+ window.hide();+ if (process.platform === "darwin") app.dock?.hide();+ this.scheduleIdle();+ this.deps.onChange();+ }++ /** Keeps the window from idling out until the returned release is called. */+ hold(): () => void {+ this.holds++;+ this.clearIdle();+ if (this.holds === 1) this.deps.onChange();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.holds--;+ this.scheduleIdle();+ if (this.holds === 0) this.deps.onChange();+ };+ }++ /** Work the renderer started itself (an export from the UI) that must not be cut off. */+ setBusy(busy: boolean): void {+ this.busy = busy;+ if (busy) this.clearIdle();+ else this.scheduleIdle();+ }++ private scheduleIdle(): void {+ this.clearIdle();+ if (!this.idle()) return;+ this.idleTimer = setTimeout(() => {+ this.idleTimer = null;+ if (this.idle()) this.current()?.destroy();+ }, this.deps.idleMs);+ }++ private idle(): boolean {+ return this.current() !== null && !this.shown && this.holds === 0 && !this.busy;+ }++ private clearIdle(): void {+ if (this.idleTimer) clearTimeout(this.idleTimer);+ this.idleTimer = null;+ }+}diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsxindex ef797f42..7e6527b2 100644--- a/apps/web/src/app.tsx+++ b/apps/web/src/app.tsx@@ -4,7 +4,7 @@import { Router, HashRouter, Route, useLocation } from '@solidjs/router';import { ColorModeProvider } from '@kobalte/core';-import { Show, createEffect, type JSX } from 'solid-js';+import { Show, createEffect, createMemo, type JSX } from 'solid-js';import { Toaster } from "@/components/ui/sonner";import { AppContextMenu } from "@/components/app-context-menu";@@ -14,6 +14,7 @@ import { useColorMode } from "@kobalte/core";import { mainBridge } from "@/lib/ipc";import { MAIN_CHANNELS } from "@desktop/main-channels";import { EditorApi } from '@/dapi';+import { renderOverlay } from '@/context/render';import { UpgradeDialog } from '@/components/upgrade-dialog';import { PurchaseSuccess } from '@/components/purchase-success';import { ScreenTooSmall } from '@/components/screen-too-small';@@ -62,6 +63,20 @@ function TitleBarColorMode() {return null;}+// A render goes on when the user closes the window, which only hides it;+// main is told, so the hidden window is not torn down under it once idle.+function ReportRendering() {+ const rendering = createMemo(() => renderOverlay() !== null);++ createEffect(() => {+ if (window.desktop) {+ mainBridge.call(MAIN_CHANNELS.WINDOW_SET_BUSY, { busy: rendering() });+ }+ });++ return null;+}+function EnvironmentOverlays() {const location = useLocation();const onCheckoutPage = () => location.pathname.startsWith('/checkout');@@ -93,6 +108,7 @@ function App() {<EnvironmentOverlays /><PersistRoute /><TitleBarColorMode />+ <ReportRendering /></ColorModeProvider>)}>diff --git a/apps/web/src/dapi/handler.ts b/apps/web/src/dapi/handler.tsindex d2964f9b..b7c946dc 100644--- a/apps/web/src/dapi/handler.ts+++ b/apps/web/src/dapi/handler.ts@@ -30,6 +30,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" | "report">;+export type ServedToolName = Exclude<ToolName, "logs" | "report" | "window">;export type Handlers = { readonly [N in ServedToolName]: ToolHandler<N> };diff --git a/docs/reference/tools/README.md b/docs/reference/tools/README.mdindex f98498f2..30dc7378 100644--- a/docs/reference/tools/README.md+++ b/docs/reference/tools/README.md@@ -48,6 +48,7 @@ Every tool runs inside the app, so the app has to be running. Over MCP that is a| [`voices`](./voices.md) | `diffusion voices` | Speech voices || [`logs`](./logs.md) | `diffusion logs` | App logs || [`screenshot`](./screenshot.md) | `diffusion screenshot` | Window screenshot |+| [`window`](./window.md) | `diffusion window` | App window || [`fonts`](./fonts.md) | `diffusion fonts` | Fonts || [`report`](./report.md) | `diffusion report` | Report a bug |@@ -57,7 +58,7 @@ How the surface is divided:- **Media inspection** (`media_*`): a file by path, without adding it to the project. Absolute paths and URLs work with or without an open project; library paths (`b-roll/clip.mp4`) need one.- **Masks.** [`media_segment`](./media/segment.md) segments and tracks an object in footage and writes the mask file a `<mask src>` names.- **What a declaration may name.** [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md). Generation itself is declared in the project module (`generate.*`, see [jsx/generate.md](../jsx/generate.md)); no tool generates.-- **The app and the machine.** [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`report`](./report.md).+- **The app and the machine.** [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`window`](./window.md), [`report`](./report.md).## Downloading footagediff --git a/docs/reference/tools/window.md b/docs/reference/tools/window.mdnew file mode 100644index 00000000..ea3756a4--- /dev/null+++ b/docs/reference/tools/window.md@@ -0,0 +1,28 @@+# window++Show or hide the app's editor window, or, without arguments, report whether it is showing. The app runs in the background while agents use it: no tool raises the window, and every tool works while it is hidden. Show it when the user asks to see the project or to edit by hand; it opens on the project last opened. The user closing the window only hides it again.++| | |+| --- | --- |+| MCP tool | `window` |+| CLI | `diffusion window [show\|hide]` |++## Input++| Field | Type | CLI | Description |+| --- | --- | --- | --- |+| `visible` | `boolean` | `show` / `hide` | true to show and focus the window, false to hide it (default: leave it as it is) |++The app lives in the menu bar (macOS) or the notification area (Windows). While the window is hidden it has no Dock icon, and after ten minutes hidden and unused the window itself is closed to free its memory; the next tool call, or showing it, opens it again on the same project. Closing the window, from its title bar or with ⌘W, hides it; only Quit, from the tray or ⌘Q, ends the app.++## Output++One JSON object: whether the window is showing after the call. A minimized window counts as showing.++```ts+{ visible: boolean }+```++## Errors++Fails when `visible` is not a boolean, or the CLI's state is neither `show` nor `hide`.diff --git a/packages/dapi/src/catalog.test.ts b/packages/dapi/src/catalog.test.tsindex 77199df9..75749849 100644--- a/packages/dapi/src/catalog.test.ts+++ b/packages/dapi/src/catalog.test.ts@@ -49,6 +49,7 @@ describe("catalog", () => {expect(toolByName("capture").environment).toBe("renderer");expect(toolByName("fonts").environment).toBe("renderer");expect(toolByName("logs").environment).toBe("main");+ expect(toolByName("window").environment).toBe("main");expect(isToolName("media_grab")).toBe(true);expect(isToolName("media.frame")).toBe(false);});diff --git a/packages/dapi/src/catalog.ts b/packages/dapi/src/catalog.tsindex 466941af..7821d416 100644--- a/packages/dapi/src/catalog.ts+++ b/packages/dapi/src/catalog.ts@@ -23,6 +23,7 @@ import { mediaListen } from "./tools/media-listen";import { mediaSegment } from "./tools/media-segment";import { fonts } from "./tools/fonts";import { report } from "./tools/report";+import { appWindow } from "./tools/window";/*** Every tool, in the order a listing shows them: the project loop first@@ -46,6 +47,7 @@ export const catalog = [voices,logs,screenshot,+ appWindow,fonts,report,] as const;diff --git a/packages/dapi/src/tools/window.ts b/packages/dapi/src/tools/window.tsnew file mode 100644index 00000000..7b9c5359--- /dev/null+++ b/packages/dapi/src/tools/window.ts@@ -0,0 +1,20 @@+/* 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 { z } from "zod";+import { defineTool } from "../tool";++export const appWindow = defineTool({+ name: "window",+ title: "App window",+ description:+ "Show or hide the app's editor window, or, without arguments, report whether it is showing. The app runs in the background while agents use it: no tool raises the window, and every tool works while it is hidden. Show it when the user asks to see the project or to edit by hand; it opens on the project last opened. The user closing the window only hides it again.",+ input: z.object({+ visible: z.boolean().optional().describe("true to show and focus the window, false to hide it (default: leave it as it is)"),+ }),+ output: z.object({+ visible: z.boolean().describe("whether the window is showing now"),+ }),+ environment: "main",+});diff --git a/packages/reconciler/src/evaluate.ts b/packages/reconciler/src/evaluate.tsindex bf4987b9..f1e85a72 100644--- a/packages/reconciler/src/evaluate.ts+++ b/packages/reconciler/src/evaluate.ts@@ -27,7 +27,7 @@ export function evaluate(code: string): () => unknown {return resolved;};- new Function('require', 'module', 'exports', code)(require, module, module.exports);+ new Function('require', 'module', 'exports', `${code}\n//# sourceURL=project.js`)(require, module, module.exports);const component = module.exports.default;if (typeof component !== 'function') {