Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(mcp): make closed-project edits atomic and undoable
EtienneLescot3c6d94e76f88
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex 3a2e6d0ac..5f8d3f5ff 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -799,5 +799,73 @@ describe("DocumentService", () => {expect((await service.getProject(doc.project.id)).annotations).toHaveLength(7);});++ it("makes a read wait for a save already queued", async () => {+ const doc = await service.createProject("Read after write");+ const saving = service.saveProject({ ...doc, project: { ...doc.project, title: "Saved" } });+ expect((await service.getProject(doc.project.id)).project.title).toBe("Saved");+ await saving;+ });+ });++ // The MCP server saves projects the editor does not hold. If the editor opens one+ // between that read and that save, it loads the file without the save and its own+ // next save drops it without a word.+ describe("saveProjectIfUnchanged", () => {+ const renamed = (doc: AxcutDocument, title: string): AxcutDocument => ({+ ...doc,+ project: { ...doc.project, title },+ });++ it("saves when nothing touched the project since the read", async () => {+ const created = await service.createProject("Untouched");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ const saved = await service.saveProjectIfUnchanged(renamed(document, "Edited"), version);+ expect(saved?.project.title).toBe("Edited");+ expect((await service.getProject(created.project.id)).project.title).toBe("Edited");+ });++ it("writes nothing when the project was read since, as the editor opening it does", async () => {+ const created = await service.createProject("Opened");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ await service.getProject(created.project.id);+ expect(await service.saveProjectIfUnchanged(renamed(document, "Edited"), version)).toBeNull();+ expect((await service.getProject(created.project.id)).project.title).toBe("Opened");+ });++ it("writes nothing when a read arrives while it is queued, and that read sees the file as it is", async () => {+ const created = await service.createProject("Racing");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ // Unawaited: the editor's open lands while the save waits for its turn.+ const saving = service.saveProjectIfUnchanged(renamed(document, "Edited"), version);+ const opened = await service.getProject(created.project.id);+ expect(await saving).toBeNull();+ expect(opened.project.title).toBe("Racing");+ });++ it("writes nothing when the project was saved since", async () => {+ const created = await service.createProject("Saved");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ await service.saveProject(renamed(document, "Elsewhere"));+ expect(await service.saveProjectIfUnchanged(renamed(document, "Edited"), version)).toBeNull();+ expect((await service.getProject(created.project.id)).project.title).toBe("Elsewhere");+ });++ it("writes nothing when the file changed outside the app, updatedAt and all", async () => {+ const created = await service.createProject("External");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ const file = path.join(tempDir, `${created.project.id}.openscreen`);+ await fs.writeFile(file, JSON.stringify(renamed(document, "Synced")), "utf8");+ expect(await service.saveProjectIfUnchanged(renamed(document, "Edited"), version)).toBeNull();+ expect((await service.getProject(created.project.id)).project.title).toBe("Synced");+ });++ it("writes nothing over a project deleted since", async () => {+ const created = await service.createProject("Deleted");+ const { document, version } = await service.getProjectForUpdate(created.project.id);+ await service.deleteProject(created.project.id);+ expect(await service.saveProjectIfUnchanged(renamed(document, "Edited"), version)).toBeNull();+ await expect(service.getProject(created.project.id)).rejects.toThrow(DocumentNotFoundError);+ });});});diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.tsindex 59818d839..8045b0cba 100644--- a/electron/ai-edition/document-service.ts+++ b/electron/ai-edition/document-service.ts@@ -41,6 +41,17 @@ export interface ProjectSummary {assetCount: number;}+function stampForSave(document: AxcutDocument): AxcutDocument {+ const parsed = documentSchema.parse(document);+ return { ...parsed, project: { ...parsed.project, updatedAt: new Date().toISOString() } };+}++/** What `saveProjectIfUnchanged` checks against: the read that returned it. */+export interface ProjectVersion {+ readonly generation: number;+ readonly raw: string;+}+export interface AddAssetInput {path: string;label?: string;@@ -158,6 +169,8 @@ export class DocumentService {private legacyMigrationDone = false;/** Tail of the in-flight save chain per project id — see writeProject. */private readonly writeQueues = new Map<string, Promise<void>>();+ /** Bumped as each read or save of a project starts — see saveProjectIfUnchanged. */+ private readonly generations = new Map<string, number>();// `mediaRegistryDir` is where the media-links registry file lives// (RECORDINGS_DIR in production) — see getProject. Injected for the same@@ -286,30 +299,18 @@ export class DocumentService {}async getProject(projectId: string): Promise<AxcutDocument> {- // Prefer the canonical `.openscreen` file, falling back to a not-yet-migrated- // legacy `.axcut` so a project opened before its migration pass still loads.- let raw: string;- try {- raw = await fs.readFile(this.fileFor(projectId), "utf8");- } catch (error) {- if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {- throw new ProjectFileError(- `Failed to read project ${projectId}: ${error instanceof Error ? error.message : String(error)}`,- projectId,- );- }- try {- raw = await fs.readFile(this.legacyFileFor(projectId), "utf8");- } catch (legacyError) {- if ((legacyError as NodeJS.ErrnoException)?.code === "ENOENT") {- throw new DocumentNotFoundError(projectId);- }- throw new ProjectFileError(- `Failed to read project ${projectId}: ${legacyError instanceof Error ? legacyError.message : String(legacyError)}`,- projectId,- );- }- }+ return (await this.getProjectForUpdate(projectId)).document;+ }++ /** `getProject`, plus the version to hand `saveProjectIfUnchanged`. */+ async getProjectForUpdate(+ projectId: string,+ ): Promise<{ document: AxcutDocument; version: ProjectVersion }> {+ const generation = this.touch(projectId);+ // Behind any save already queued for this project, so a read never returns the+ // file such a save is about to replace. saveProjectIfUnchanged relies on it.+ await this.writeQueues.get(projectId);+ const raw = await this.readProjectFile(projectId);// Relink here rather than in the .openscreen import handlers, because this// is the one place every open funnels through — the project picker, the// agent, and the auto-load-last-project effect on launch. A document whose@@ -325,7 +326,39 @@ export class DocumentService {);// AFTER the relink, so what is granted is the path the renderer will actually ask for.this.onProjectRead?.(document);- return document;+ return { document, version: { generation, raw } };+ }++ private touch(projectId: string): number {+ const generation = (this.generations.get(projectId) ?? 0) + 1;+ this.generations.set(projectId, generation);+ return generation;+ }++ private async readProjectFile(projectId: string): Promise<string> {+ // Prefer the canonical `.openscreen` file, falling back to a not-yet-migrated+ // legacy `.axcut` so a project opened before its migration pass still loads.+ try {+ return await fs.readFile(this.fileFor(projectId), "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {+ throw new ProjectFileError(+ `Failed to read project ${projectId}: ${error instanceof Error ? error.message : String(error)}`,+ projectId,+ );+ }+ }+ try {+ return await fs.readFile(this.legacyFileFor(projectId), "utf8");+ } catch (legacyError) {+ if ((legacyError as NodeJS.ErrnoException)?.code === "ENOENT") {+ throw new DocumentNotFoundError(projectId);+ }+ throw new ProjectFileError(+ `Failed to read project ${projectId}: ${legacyError instanceof Error ? legacyError.message : String(legacyError)}`,+ projectId,+ );+ }}async createProject(title: string): Promise<AxcutDocument> {@@ -342,11 +375,8 @@ export class DocumentService {}async saveProject(document: AxcutDocument): Promise<AxcutDocument> {- const parsed = documentSchema.parse(document);- const stamped: AxcutDocument = {- ...parsed,- project: { ...parsed.project, updatedAt: new Date().toISOString() },- };+ const stamped = stampForSave(document);+ this.touch(stamped.project.id);await this.writeProject(stamped);// After the write, never before: a derived file is not worth delaying the user's edit// reaching disk, and a failure to generate one must not fail the save.@@ -354,6 +384,35 @@ export class DocumentService {return stamped;}+ /**+ * `saveProject` for a writer that does not hold the project open (the MCP+ * server), unless anything read or saved the project since the+ * `getProjectForUpdate` that returned `version`, or its file changed: then+ * nothing is written and this resolves null.+ *+ * The read is the case that matters: an editor that opened the project after+ * `version` holds a copy without this save, and its own next save would drop+ * it without a word. The check runs inside the project's write queue, and reads+ * wait behind that queue, so nothing in this process reads or saves the project+ * between the check and the write.+ */+ async saveProjectIfUnchanged(+ document: AxcutDocument,+ version: ProjectVersion,+ ): Promise<AxcutDocument | null> {+ const stamped = stampForSave(document);+ const projectId = stamped.project.id;+ const written = await this.writeProject(+ stamped,+ async () =>+ this.generations.get(projectId) === version.generation &&+ (await this.readProjectFile(projectId).catch(() => null)) === version.raw,+ );+ if (!written) return null;+ await ensureDocumentExtensions(stamped);+ return stamped;+ }+async deleteProject(projectId: string): Promise<void> {// Remove the canonical file and any lingering legacy `.axcut` for this id.for (const filePath of [this.fileFor(projectId), this.legacyFileFor(projectId)]) {@@ -476,15 +535,23 @@ export class DocumentService {* The queue alone would still leave a torn file on a crash; the rename alone* would still let two saves race for the same destination.*/- private writeProject(doc: AxcutDocument): Promise<void> {+ private writeProject(+ doc: AxcutDocument,+ precondition?: () => Promise<boolean>,+ ): Promise<boolean> {const projectId = doc.project.id;const tail = this.writeQueues.get(projectId) ?? Promise.resolve();+ const write = async () => {+ if (precondition && !(await precondition())) return false;+ await this.writeProjectNow(doc);+ return true;+ };// Chained on both settlements: one save failing must not cancel the next.- const run = tail.then(- () => this.writeProjectNow(doc),- () => this.writeProjectNow(doc),+ const run = tail.then(write, write);+ const settled = run.then(+ () => undefined,+ () => undefined,);- const settled = run.catch(() => undefined);this.writeQueues.set(projectId, settled);void settled.then(() => {// Only the tail clears the entry — a later save may already own it.diff --git a/electron/mcp/mcp-controller.test.ts b/electron/mcp/mcp-controller.test.tsindex bb5c79d01..290dfe14b 100644--- a/electron/mcp/mcp-controller.test.ts+++ b/electron/mcp/mcp-controller.test.ts@@ -19,10 +19,10 @@ const deps: McpToolDeps = {host: { snapshot: async () => null, apply: async () => "no-editor" },projects: {listProjects: async () => [],- getProject: async (id) => {+ getProjectForUpdate: async (id) => {throw new DocumentNotFoundError(id);},- saveProject: async (document) => document,+ saveProjectIfUnchanged: async (document) => document,},editsAllowed: () => true,version: "0.0.0",diff --git a/electron/mcp/openscreen-mcp-server.test.ts b/electron/mcp/openscreen-mcp-server.test.tsindex a47189b00..99cfcfa8b 100644--- a/electron/mcp/openscreen-mcp-server.test.ts+++ b/electron/mcp/openscreen-mcp-server.test.ts@@ -180,6 +180,9 @@ describe("the MCP tool surface", () => {expect(Object.keys(tool.inputSchema.properties ?? {})).toContain("projectId");expect(tool.inputSchema.required ?? []).not.toContain("projectId");}+ for (const tool of tools.slice(-2)) {+ expect(Object.keys(tool.inputSchema.properties ?? {})).toContain("projectId");+ }// The zod schemas survive the trip to JSON Schema with their fields intact.const addTrim = tools.find((t) => t.name === "addTrim");expect(Object.keys(addTrim?.inputSchema.properties ?? {})).toEqual(@@ -392,6 +395,24 @@ describe("checkpoints", () => {describe("projects other than the open one", () => {const addTrimArgs = { assetId: "asset_1", startSec: 5, endSec: 6 };+ /** An edit to a project that is not open is refused until it has one. */+ async function checkpoint(mcp: Client, projectId: string): Promise<string> {+ const result = await mcp.callTool({ name: "createCheckpoint", arguments: { projectId } });+ expect(result.isError).toBeFalsy();+ return JSON.parse(resultText(result)).checkpointId;+ }++ /** Runs `during` right after the next call has read its project from disk. */+ function onNextRead(during: () => unknown) {+ const getProjectForUpdate = projects.getProjectForUpdate.bind(projects);+ projects.getProjectForUpdate = async (id) => {+ projects.getProjectForUpdate = getProjectForUpdate;+ const read = await getProjectForUpdate(id);+ await during();+ return read;+ };+ }+it("lists every project and flags the one open in the editor", async () => {await projects.saveProject(fixtureDocument("proj_1"));await projects.saveProject(fixtureDocument("proj_2"));@@ -420,6 +441,7 @@ describe("projects other than the open one", () => {await projects.saveProject(fixtureDocument("proj_2"));const editor = new FakeEditor();const mcp = await connect(editor);+ await checkpoint(mcp, "proj_2");const result = await mcp.callTool({name: "addTrim",arguments: { ...addTrimArgs, projectId: "proj_2" },@@ -435,6 +457,7 @@ describe("projects other than the open one", () => {const editor = new FakeEditor();editor.document = null;const mcp = await connect(editor);+ await checkpoint(mcp, "proj_2");const result = await mcp.callTool({name: "addTrim",arguments: { ...addTrimArgs, projectId: "proj_2" },@@ -456,6 +479,23 @@ describe("projects other than the open one", () => {expect((await projects.getProject("proj_1")).timeline.trimRanges).toHaveLength(0);});+ it("reports a user edit made mid-call on the open project's id as a conflict", async () => {+ await projects.saveProject(fixtureDocument("proj_1"));+ const editor = new FakeEditor();+ editor.onSnapshot = () => {+ editor.revision += 1;+ };+ const mcp = await connect(editor);+ const result = await mcp.callTool({+ name: "addTrim",+ arguments: { ...addTrimArgs, projectId: "proj_1" },+ });+ expect(result.isError).toBe(true);+ expect(resultText(result)).toContain("NOT applied");+ expect(editor.applied).toHaveLength(0);+ expect((await projects.getProject("proj_1")).timeline.trimRanges).toHaveLength(0);+ });+it("names listProjects for an unknown id", async () => {const mcp = await connect(new FakeEditor());const result = await mcp.callTool({@@ -477,46 +517,82 @@ describe("projects other than the open one", () => {expect((await projects.getProject("proj_2")).timeline.trimRanges).toHaveLength(0);});- it("does not save over a project the editor opened mid-call", async () => {- const saved = await projects.saveProject(fixtureDocument("proj_2"));+ it("refuses an edit until the project has a checkpoint, its only undo", async () => {+ await projects.saveProject(fixtureDocument("proj_2"));+ const mcp = await connect(new FakeEditor());+ const result = await mcp.callTool({+ name: "addTrim",+ arguments: { ...addTrimArgs, projectId: "proj_2" },+ });+ expect(result.isError).toBe(true);+ expect(resultText(result)).toContain("createCheckpoint");+ expect((await projects.getProject("proj_2")).timeline.trimRanges).toHaveLength(0);+ });++ it("reverts a series of edits to its file in one restore", async () => {+ await projects.saveProject(fixtureDocument("proj_2"));+ const before = await projects.getProject("proj_2");const editor = new FakeEditor();- const getProject = projects.getProject.bind(projects);- let reads = 0;- projects.getProject = async (id) => {- const document = await getProject(id);- if (++reads === 1) editor.document = saved;- return document;- };const mcp = await connect(editor);+ const checkpointId = await checkpoint(mcp, "proj_2");+ for (const startSec of [5, 10]) {+ await mcp.callTool({+ name: "addTrim",+ arguments: { assetId: "asset_1", startSec, endSec: startSec + 1, projectId: "proj_2" },+ });+ }+ expect((await projects.getProject("proj_2")).timeline.trimRanges).toHaveLength(2);++ const result = await mcp.callTool({+ name: "restoreCheckpoint",+ arguments: { checkpointId, projectId: "proj_2" },+ });+ expect(result.isError).toBeFalsy();+ const after = await projects.getProject("proj_2");+ expect(after.timeline).toEqual(before.timeline);+ expect(editor.applied).toHaveLength(0);+ });++ it("names the projectId a closed project's checkpoint needs, and restores nothing without it", async () => {+ await projects.saveProject(fixtureDocument("proj_2"));+ const editor = new FakeEditor();+ const mcp = await connect(editor);+ const checkpointId = await checkpoint(mcp, "proj_2");+ const result = await mcp.callTool({ name: "restoreCheckpoint", arguments: { checkpointId } });+ expect(result.isError).toBe(true);+ expect(resultText(result)).toContain('"proj_2"');+ expect(editor.applied).toHaveLength(0);+ });++ // The editor's open has read the file but not yet installed it, so it does not+ // show in a snapshot: only the read itself gives it away.+ it("does not save over a project the editor is opening mid-call", async () => {+ await projects.saveProject(fixtureDocument("proj_2"));+ const mcp = await connect(new FakeEditor());+ await checkpoint(mcp, "proj_2");+ onNextRead(() => projects.getProject("proj_2"));const result = await mcp.callTool({name: "addTrim",arguments: { ...addTrimArgs, projectId: "proj_2" },});expect(result.isError).toBe(true);expect(resultText(result)).toContain("NOT applied");- expect((await getProject("proj_2")).timeline.trimRanges).toHaveLength(0);+ expect((await projects.getProject("proj_2")).timeline.trimRanges).toHaveLength(0);});- it("does not save over a project saved elsewhere mid-call", async () => {+ it("does not save over a project saved elsewhere mid-call, even in the same millisecond", async () => {const saved = await projects.saveProject(fixtureDocument("proj_2"));- const getProject = projects.getProject.bind(projects);- let reads = 0;- projects.getProject = async (id) => {- const document = await getProject(id);- if (++reads === 1) {- // updatedAt has millisecond resolution; make sure the second save moves it.- await new Promise((resolve) => setTimeout(resolve, 5));- await projects.saveProject({ ...saved, project: { ...saved.project, title: "Renamed" } });- }- return document;- };const mcp = await connect(new FakeEditor());+ await checkpoint(mcp, "proj_2");+ onNextRead(() =>+ projects.saveProject({ ...saved, project: { ...saved.project, title: "Renamed" } }),+ );const result = await mcp.callTool({name: "addTrim",arguments: { ...addTrimArgs, projectId: "proj_2" },});expect(result.isError).toBe(true);- const onDisk = await getProject("proj_2");+ const onDisk = await projects.getProject("proj_2");expect(onDisk.project.title).toBe("Renamed");expect(onDisk.timeline.trimRanges).toHaveLength(0);});@@ -524,24 +600,19 @@ describe("projects other than the open one", () => {it("does not save over a change that kept the file's updatedAt", async () => {const saved = await projects.saveProject(fixtureDocument("proj_2"));const file = path.join(dir, "projects", "proj_2.openscreen");- const getProject = projects.getProject.bind(projects);- let reads = 0;- projects.getProject = async (id) => {- const document = await getProject(id);- if (++reads === 1) {- // A writer outside the app (a sync tool, a restored copy): same stamp, new content.- const renamed = { ...saved, project: { ...saved.project, title: "Renamed" } };- writeFileSync(file, JSON.stringify(renamed));- }- return document;- };const mcp = await connect(new FakeEditor());+ await checkpoint(mcp, "proj_2");+ // A writer outside the app (a sync tool, a restored copy): same stamp, new content.+ onNextRead(() => {+ const renamed = { ...saved, project: { ...saved.project, title: "Renamed" } };+ writeFileSync(file, JSON.stringify(renamed));+ });const result = await mcp.callTool({name: "addTrim",arguments: { ...addTrimArgs, projectId: "proj_2" },});expect(result.isError).toBe(true);- const onDisk = await getProject("proj_2");+ const onDisk = await projects.getProject("proj_2");expect(onDisk.project.title).toBe("Renamed");expect(onDisk.timeline.trimRanges).toHaveLength(0);});diff --git a/electron/mcp/openscreen-mcp-server.ts b/electron/mcp/openscreen-mcp-server.tsindex 04add2358..1b0c1d49a 100644--- a/electron/mcp/openscreen-mcp-server.ts+++ b/electron/mcp/openscreen-mcp-server.ts@@ -12,15 +12,16 @@// the same revision-guarded apply, so a user edit landing mid-call is never// overwritten and every edit is one undo step.//-// Two tools exist only here: `createCheckpoint` / `restoreCheckpoint`. A client-// chains several edits per turn, and undo is per call, so they give it one step-// back to where the turn started. The in-app agent has no need for them: its-// whole turn is already a single apply.-//// A call can name another project with `projectId` (see `listProjects`). The// project open in the editor is still only ever edited through the editor; any-// other one is read from and saved to its file, guarded against the editor-// opening it, or anything else saving it, while the call ran.+// other one is read from and saved to its file, refused if anything read or saved+// that project while the call ran (`saveProjectIfUnchanged`).+//+// Two tools exist only here: `createCheckpoint` / `restoreCheckpoint`. A client+// chains several edits per turn, and undo is per call, so they give it one step+// back to where the turn started. For a project that is not open they are the+// only way back, so an edit to one is refused until it has a checkpoint. The+// in-app agent has no need for them: its whole turn is already a single apply.//// The HTTP layer is local-only: bound to 127.0.0.1, a bearer token on every// request, and a Host/Origin check so a web page cannot reach it by DNS@@ -34,7 +35,7 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";import { z } from "zod";import { type AxcutDocument, documentSchema } from "../../src/lib/ai-edition/schema";-import { isMutatingTool } from "../ai-edition/agent-tools";+import { type AgentToolExecution, isMutatingTool } from "../ai-edition/agent-tools";import {buildSystemPrompt,type CursorTelemetryReader,@@ -43,7 +44,11 @@ import {TOOL_ARG_SCHEMAS,TOOL_DESCRIPTIONS,} from "../ai-edition/deep-agent/service";-import { DocumentNotFoundError, type ProjectSummary } from "../ai-edition/document-service";+import {+ DocumentNotFoundError,+ type ProjectSummary,+ type ProjectVersion,+} from "../ai-edition/document-service";export const MCP_SERVER_NAME = "openscreen";export const MCP_ENDPOINT_PATH = "/mcp";@@ -75,8 +80,14 @@ export interface McpDocumentHost {export interface McpProjectStore {listProjects(): Promise<ProjectSummary[]>;/** Throws `DocumentNotFoundError` for an unknown id. */- getProject(projectId: string): Promise<AxcutDocument>;- saveProject(document: AxcutDocument): Promise<AxcutDocument>;+ getProjectForUpdate(+ projectId: string,+ ): Promise<{ document: AxcutDocument; version: ProjectVersion }>;+ /** `null`, and nothing written, when the project was read or saved since `version`. */+ saveProjectIfUnchanged(+ document: AxcutDocument,+ version: ProjectVersion,+ ): Promise<AxcutDocument | null>;}export interface McpToolDeps {@@ -93,8 +104,12 @@ export const LIST_PROJECTS_TOOL = "listProjects";const LIST_PROJECTS_DESCRIPTION ="List every OpenScreen project: id, title, last update, asset count, and whether it is the one open in the editor. Pass a project's id as `projectId` to any other tool to read or edit that project.";-const PROJECT_ID_DESCRIPTION =- "The project to act on, from listProjects. Omit it for the project open in the editor.";+const PROJECT_ID_ARG = z+ .string()+ .optional()+ .describe(+ "The project to act on, from listProjects. Omit it for the project open in the editor.",+ );const NO_PROJECT_MESSAGE ="No project is open in the OpenScreen editor. Call listProjects and pass a projectId, or ask the user to open one in OpenScreen.";@@ -104,6 +119,9 @@ const NO_PROJECT_MESSAGE =const PROJECT_CHANGED_MESSAGE ="The edit was NOT applied: the project was opened in the editor or saved elsewhere while this call ran. Call getCurrentDocument with the same projectId to re-read it, then retry.";+const CHECKPOINT_REQUIRED_MESSAGE =+ "The edit was NOT applied: this project is not open in the editor, so the user cannot undo an edit to it with Ctrl/Cmd+Z. Call createCheckpoint with this projectId first, so restoreCheckpoint can take your edits back in one step, then retry.";+const APPLY_FAILURE_MESSAGES: Record<Exclude<McpApplyResult, "applied">, string> = {conflict:"The edit was NOT applied: the project changed in the editor while this call ran. Call getCurrentDocument to re-read it, then retry.",@@ -124,7 +142,7 @@ const DESTRUCTIVE_TOOLS: ReadonlySet<string> = new Set([const MCP_PREAMBLE = ["These tools act on the user's OpenScreen projects. Without a projectId they act on the project open in the editor; call listProjects to find any other project and pass its id as projectId. Every edit is saved straight away. An edit to the open project appears in the editor, where the user can undo it with Ctrl/Cmd+Z; an edit to any other project is saved to its file and is not on the editor's undo stack. Nothing here records, exports or imports media.",- "Before a series of edits, call createCheckpoint. Undo is one step per call, so if the result is not what the user wanted, restoreCheckpoint takes the project back in one step instead of many.",+ "Before a series of edits, call createCheckpoint with the same projectId. Undo is one step per call, so if the result is not what the user wanted, restoreCheckpoint takes the project back in one step instead of many. A project that is not open in the editor cannot be edited until it has a checkpoint, since restoreCheckpoint is its only undo.","",].join("\n");@@ -136,14 +154,14 @@ const CHECKPOINT_TOOLS = [{name: "createCheckpoint",description:- "Save the current state of the open project and return its checkpointId. Changes nothing. Call it before a series of edits so restoreCheckpoint can revert all of them in one step.",+ "Save the current state of the project and return its checkpointId. Changes nothing. Call it before a series of edits so restoreCheckpoint can revert all of them in one step.",inputSchema: z.object({}),mutating: false,},{name: "restoreCheckpoint",description:- "Put the open project back exactly as it was when createCheckpoint returned this checkpointId, discarding every edit made since, including the user's. Lands as one undo step, so the user can undo the restore itself.",+ "Put the project back exactly as it was when createCheckpoint returned this checkpointId, discarding every edit made since, including the user's. Pass the same projectId as to createCheckpoint. On the project open in the editor it lands as one undo step, so the user can undo the restore itself.",inputSchema: z.object({ checkpointId: z.string() }),mutating: true,},@@ -178,7 +196,7 @@ export function createToolRunner(deps: McpToolDeps) {let queue: Promise<unknown> = Promise.resolve();const checkpoints = new Map<string, AxcutDocument>();- function createCheckpoint(document: AxcutDocument): CallToolResult {+ function createCheckpoint(document: AxcutDocument): AgentToolExecution {const checkpointId = `cp_${randomUUID()}`;checkpoints.set(checkpointId, document);// A Map iterates in insertion order: the first key is the oldest.@@ -186,37 +204,45 @@ export function createToolRunner(deps: McpToolDeps) {if (checkpoints.size <= MAX_CHECKPOINTS) break;checkpoints.delete(oldest);}- return textResult(JSON.stringify({ checkpointId }), false);+ return { ok: true, resultJson: JSON.stringify({ checkpointId }) };}- async function restoreCheckpoint(- document: AxcutDocument,- revision: number,- args: unknown,- ): Promise<CallToolResult> {+ /** Hands the checkpoint back as the call's new document, saved like any edit. */+ function restoreCheckpoint(document: AxcutDocument, args: unknown): AgentToolExecution {if (!deps.editsAllowed()) {- return textResult(- "Project edits are turned off in OpenScreen, so the checkpoint was NOT restored. Ask the user to re-enable 'Project edits' in Settings → AI, or to undo the edits themselves.",- true,- );+ return {+ ok: false,+ resultJson:+ "Project edits are turned off in OpenScreen, so the checkpoint was NOT restored. Ask the user to re-enable 'Project edits' in Settings → AI, or to undo the edits themselves.",+ };}const id = (args as { checkpointId?: unknown } | null)?.checkpointId;const checkpoint = typeof id === "string" ? checkpoints.get(id) : undefined;if (!checkpoint) {- return textResult(- "Unknown checkpointId. Checkpoints last until OpenScreen quits, and only the 20 most recent are kept.",- true,- );+ return {+ ok: false,+ resultJson:+ "Unknown checkpointId. Checkpoints last until OpenScreen quits, and only the 20 most recent are kept.",+ };}if (checkpoint.project.id !== document.project.id) {- return textResult(- "The edit was NOT applied: this checkpoint belongs to another project than the one open in the editor.",- true,- );+ return {+ ok: false,+ resultJson: `The edit was NOT applied: this checkpoint belongs to another project than the one this call acts on. Pass projectId "${checkpoint.project.id}".`,+ };+ }+ return {+ ok: true,+ resultJson: JSON.stringify({ ok: true, restored: id }),+ document: checkpoint,+ };+ }++ function hasCheckpoint(projectId: string): boolean {+ for (const checkpoint of checkpoints.values()) {+ if (checkpoint.project.id === projectId) return true;}- const applied = await deps.host.apply(checkpoint, revision);- if (applied !== "applied") return textResult(APPLY_FAILURE_MESSAGES[applied], true);- return textResult(JSON.stringify({ ok: true, restored: id }), false);+ return false;}async function listProjects(): Promise<CallToolResult> {@@ -239,10 +265,7 @@ export function createToolRunner(deps: McpToolDeps) {if (!parsed.success) {return textResult("The project open in the editor could not be read.", true);}- const document = parsed.data;- if (name === "createCheckpoint") return createCheckpoint(document);- if (name === "restoreCheckpoint") return restoreCheckpoint(document, snapshot.revision, args);- const execution = await execute(document, name, args);+ const execution = await execute(parsed.data, name, args);if (execution.document) {const applied = await deps.host.apply(execution.document, snapshot.revision);if (applied !== "applied") return textResult(APPLY_FAILURE_MESSAGES[applied], true);@@ -256,39 +279,39 @@ export function createToolRunner(deps: McpToolDeps) {name: string,args: unknown,): Promise<CallToolResult> {- let document: AxcutDocument;- try {- document = await deps.projects.getProject(projectId);- } catch (error) {- if (error instanceof DocumentNotFoundError) {- return textResult(- `No project has the id "${projectId}". Call listProjects for the valid ids.`,- true,- );- }+ const read = await deps.projects.getProjectForUpdate(projectId).catch((error) => {+ if (error instanceof DocumentNotFoundError) return null;throw error;+ });+ if (!read) {+ return textResult(+ `No project has the id "${projectId}". Call listProjects for the valid ids.`,+ true,+ );}- const execution = await execute(document, name, args);+ const execution = await execute(read.document, name, args);if (execution.document) {- // Checked after the tool ran, right before the save, since that is the- // window this guard is about: the editor opening the project, or any- // save (an older editor session, the in-app agent) moving its file on.- if (openProjectId(await deps.host.snapshot()) === projectId) {- return textResult(PROJECT_CHANGED_MESSAGE, true);+ // A restore IS the way back, so it needs no checkpoint of its own.+ if (name !== "restoreCheckpoint" && !hasCheckpoint(projectId)) {+ return textResult(CHECKPOINT_REQUIRED_MESSAGE, true);}- // The whole document, not just `updatedAt`: two saves inside one- // millisecond share a stamp, and a writer outside the app (a sync tool,- // a restored copy) may not touch it at all.- const onDisk = await deps.projects.getProject(projectId);- if (JSON.stringify(onDisk) !== JSON.stringify(document)) {+ // Refused if anything read the project since (the editor opening it would+ // otherwise drop this edit on its next save) or saved it, inside the app or+ // not: see saveProjectIfUnchanged.+ if (!(await deps.projects.saveProjectIfUnchanged(execution.document, read.version))) {return textResult(PROJECT_CHANGED_MESSAGE, true);}- await deps.projects.saveProject(execution.document);}return textResult(execution.resultJson, !execution.ok);}- async function execute(document: AxcutDocument, name: string, args: unknown) {+ async function execute(+ document: AxcutDocument,+ name: string,+ args: unknown,+ ): Promise<AgentToolExecution> {+ if (name === "createCheckpoint") return createCheckpoint(document);+ if (name === "restoreCheckpoint") return restoreCheckpoint(document, args);const availableByAssetId = await probeCursorTelemetry(document, deps.cursor);return runDocumentTool(document, name, args, deps.editsAllowed(), {cursor: deps.cursor,@@ -342,9 +365,7 @@ export function createOpenScreenMcpServer(name,{description: TOOL_DESCRIPTIONS[name],- inputSchema: schema.extend({- projectId: z.string().optional().describe(PROJECT_ID_DESCRIPTION),- }),+ inputSchema: schema.extend({ projectId: PROJECT_ID_ARG }),annotations: {readOnlyHint: !mutating,destructiveHint: DESTRUCTIVE_TOOLS.has(name),@@ -359,7 +380,7 @@ export function createOpenScreenMcpServer(tool.name,{description: tool.description,- inputSchema: tool.inputSchema,+ inputSchema: tool.inputSchema.extend({ projectId: PROJECT_ID_ARG }),annotations: {readOnlyHint: !tool.mutating,destructiveHint: tool.mutating,diff --git a/technical-documentation/architecture/mcp-server.md b/technical-documentation/architecture/mcp-server.mdindex 164040fc5..510635b98 100644--- a/technical-documentation/architecture/mcp-server.md+++ b/technical-documentation/architecture/mcp-server.md@@ -18,7 +18,7 @@ Nothing about the tools is reimplemented. The server registers `TOOL_ARG_SCHEMASSo a tool added to the agent appears over MCP with no further work, and the MCP test asserts the listed tools equal `listProjects`, then `OPENSCREEN_TOOL_NAMES`, then the two checkpoint tools below. What the server adds:- **`listProjects`**, a tool of its own: every project's id, title, `updatedAt`, asset count, and `open` for the one in the editor.-- **An optional `projectId` on every agent tool**, added to its schema with `.extend()` at registration and stripped again before the call reaches the executor, which never sees it. See [Which project a call acts on](#which-project-a-call-acts-on).+- **An optional `projectId` on every agent tool and both checkpoint tools**, added to its schema with `.extend()` at registration and stripped again before the call reaches the executor, which never sees it. See [Which project a call acts on](#which-project-a-call-acts-on).- **`createCheckpoint` / `restoreCheckpoint`**, see [Checkpoints](#checkpoints).- MCP metadata: `readOnlyHint` for the reads (`!isMutatingTool`), `listProjects` and `createCheckpoint`, and `destructiveHint` for `replaceTimeline`, the three `remove*` tools and `restoreCheckpoint`.@@ -30,7 +30,7 @@ So a tool added to the agent appears over MCP with no further work, and the MCP|---|---|| omitted | The project open in the editor, through the editor. With none open the call fails with "No project is open" and points at `listProjects`. || the open project's id | The same: through the editor, never its file. |-| any other id | That project's file, through the app's one `DocumentService` (`getProject` → tool → `saveProject`). Works with no editor window at all. |+| any other id | That project's file, through the app's one `DocumentService` (`getProjectForUpdate` → tool → `saveProjectIfUnchanged`). Works with no editor window at all. A write needs a checkpoint of that project first. |The open project is never written to disk from here because the editor holds it in memory and saves it as a whole: a file edit under it would be overwritten by the editor's next save, and the editor would never show it.@@ -50,18 +50,22 @@ Only the webContents that registered on `ai-edition.mcp-host` is asked, and only### Any other project-Read with `DocumentService.getProject` (migrated and relinked, like any open) and, if the tool changed it, saved with `saveProject` — the same instance every other save in the app goes through, so its per-project write queue still holds. There is no revision to guard with, so right before the save two checks run, and either one refuses the edit with "NOT applied … re-read, then retry":+Read with `DocumentService.getProjectForUpdate` (`getProject`, migrated and relinked like any open, plus a version) and, if the tool changed it, saved with `saveProjectIfUnchanged` — the same instance every other save in the app goes through, so its per-project write queue still holds. There is no revision to guard with, so the save is refused with "NOT applied … re-read, then retry" when, since the read:-1. **The editor has not opened it meanwhile.** The editor is asked for a snapshot again; if its project is now this one, the edit is left to it. The client's retry, with the same `projectId`, then goes through the editor.-2. **Nothing else changed it meanwhile.** The file is re-read and must still be, in full, the document the tool ran against. Comparing `project.updatedAt` alone is not enough: two saves inside one millisecond share a stamp, and a writer outside the app (a sync tool, a restored copy) may not touch it.+1. **Anything read the project.** This is the editor opening it: from that read on it holds a copy without the MCP edit, and its next save would drop the edit without a word. A snapshot cannot see this in time, since the editor installs what it read only after the read returns. `DocumentService` counts every read and save of a project instead. The client's retry, with the same `projectId`, then goes through the editor.+2. **Anything saved it, or its file changed.** The file must still be, byte for byte, the one the tool ran against. This also covers a writer outside the app (a sync tool, a restored copy) and a delete.-An edit made this way is saved, but it is not on any undo stack: the editor never held it. It is in the project the next time it is opened.+The check runs inside the project's write queue, and `getProject` waits behind that queue, so nothing in the app reads or saves the project between the check and the write.++An edit made this way is saved, but it is not on any undo stack: the editor never held it. Its undo is a checkpoint, so the write is refused until the client has created one for that project (below).## CheckpointsA client chains several edits in one turn, and each is its own undo step, so reverting a turn by hand means one Ctrl+Z per call, interleaved with whatever the user did meanwhile. `createCheckpoint` saves the live document in the main process and returns a `checkpointId`; `restoreCheckpoint` applies that document back through the same revision-guarded apply, so the whole revert is **one undo step** the user can itself undo. The server instructions tell the client to checkpoint before a series of edits.-- A restore is a write: refused while MCP "Project edits" is off, and refused when the checkpoint's project id is not the open project's.+- They take `projectId` like every tool, so a project that is not open has them too: the checkpoint is read from its file, and the restore is saved to it with the same guard as any edit. That restore is not one undo step, since nothing holds the project's history.+- **A project that is not open cannot be edited without one.** Ctrl+Z cannot reach an edit to it, so a write there is refused until a checkpoint of that project is in memory, and the client is told to call `createCheckpoint` first. The server instructions say so up front.+- A restore is a write: refused while MCP "Project edits" is off, and refused when the checkpoint belongs to another project than the one the call acts on. That message names the checkpoint's `projectId`: restoring a closed project's checkpoint takes it explicitly.- It discards every edit since the checkpoint, the user's included. The tool description says so.- Checkpoints live in memory, the 20 most recent. They are lost when the app quits or the server is turned off. The in-app agent does not need them: its whole turn is a single apply.@@ -90,6 +94,6 @@ codex mcp add openscreen --url http://127.0.0.1:47821/mcp --bearer-token-env-var## Known gaps- **Only what the agent can do.** The server exposes the agent's timeline tools. Recording, export, import and project management are not tools, for MCP or for the in-app agent.-- **The file guard has a window.** The two checks run immediately before `saveProject`, not atomically with it: the editor opening the project in the few milliseconds between them and the write would load the old file, and its next save would drop the MCP edit. Closing it would need a lock the editor takes on open.-- **No undo for edits to closed projects.** See above.+- **No Ctrl+Z for edits to closed projects.** Their undo is the checkpoint the write requires, which lives in memory: it is gone once the app quits or 20 newer ones push it out, and the edits stay.+- **An editor that stops answering looks closed.** A snapshot unanswered for 30 s reads as "no project open", so an edit naming the project that editor holds would go to its file, and the editor's next save would drop it. It takes a renderer hung for 30 s.- **No project management.** Projects can be listed, read and edited, not created, renamed or deleted.