Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(mcp): read a named project before asking the editor about it

EtienneLescot84c74c9dffc2
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 6abb18653..6aa31e74e 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -800,6 +800,16 @@ describe("DocumentService", () => {
expect((await service.getProject(doc.project.id)).annotations).toHaveLength(7);
});
+ it("makes a read wait for a read asked for before it", async () => {
+ const doc = await service.createProject("Reads in order");
+ const order: string[] = [];
+ await Promise.all([
+ service.getProject(doc.project.id).then(() => order.push("first")),
+ service.getProject(doc.project.id).then(() => order.push("second")),
+ ]);
+ expect(order).toEqual(["first", "second"]);
+ });
+
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" } });
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index 1e3cf1c81..bcbee41c4 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -167,7 +167,7 @@ export class DocumentService {
private readonly projectsRoot: string;
private readonly mediaRegistryDir: string;
private legacyMigrationDone = false;
- /** Tail of the in-flight save chain per project id — see writeProject. */
+ /** Tail of the in-flight read and 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>();
@@ -307,10 +307,16 @@ export class DocumentService {
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);
+ // In the project's queue: behind its saves, so a read never returns the file one
+ // is about to replace, and behind its other reads, so a read asked for earlier
+ // has returned first. saveProjectIfUnchanged and the MCP server rely on both.
+ return this.enqueue(projectId, async () => {
+ const raw = await this.readProjectFile(projectId);
+ return { document: await this.parseProjectFile(raw), version: { generation, raw } };
+ });
+ }
+
+ private async parseProjectFile(raw: string): Promise<AxcutDocument> {
// 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
@@ -326,13 +332,13 @@ export class DocumentService {
);
// AFTER the relink, so what is granted is the path the renderer will actually ask for.
this.onProjectRead?.(document);
- return { document, version: { generation, raw } };
+ return document;
}
/**
* For a read of a project file that bypasses getProject: the open-file dialog,
* which then saves back what it read. If the file is one of this service's
- * projects, that counts as a read of it, behind its queued saves, exactly as in
+ * projects, that counts as a read of it, behind its queued reads and saves, as in
* getProject. Any other file is not this service's business.
*/
async beforeProjectFileRead(filePath: string): Promise<void> {
@@ -557,15 +563,18 @@ export class DocumentService {
doc: AxcutDocument,
precondition?: () => Promise<boolean>,
): Promise<boolean> {
- const projectId = doc.project.id;
- const tail = this.writeQueues.get(projectId) ?? Promise.resolve();
- const write = async () => {
+ return this.enqueue(doc.project.id, async () => {
if (precondition && !(await precondition())) return false;
await this.writeProjectNow(doc);
return true;
- };
+ });
+ }
+
+ /** Runs `step` once every read and save of the project asked for before it is done. */
+ private enqueue<T>(projectId: string, step: () => Promise<T>): Promise<T> {
+ const tail = this.writeQueues.get(projectId) ?? Promise.resolve();
// Chained on both settlements: one save failing must not cancel the next.
- const run = tail.then(write, write);
+ const run = tail.then(step, step);
const settled = run.then(
() => undefined,
() => undefined,
diff --git a/electron/mcp/openscreen-mcp-server.test.ts b/electron/mcp/openscreen-mcp-server.test.ts
index 99cfcfa8b..b3d75df5e 100644
--- a/electron/mcp/openscreen-mcp-server.test.ts
+++ b/electron/mcp/openscreen-mcp-server.test.ts
@@ -3,11 +3,12 @@
// DocumentService on a temp directory for the projects that are not open.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import fsPromises from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
type AxcutDocument,
createEmptyDocument,
@@ -564,6 +565,35 @@ describe("projects other than the open one", () => {
expect(editor.applied).toHaveLength(0);
});
+ // The editor was already reading the file when the call came in, and installs what
+ // it read as soon as that read returns.
+ it("waits out an editor open already under way, then edits through the editor", async () => {
+ await projects.saveProject(fixtureDocument("proj_2"));
+ const editor = new FakeEditor();
+ const mcp = await connect(editor);
+ await checkpoint(mcp, "proj_2");
+ const readFile = fsPromises.readFile;
+ const slowRead = vi.spyOn(fsPromises, "readFile").mockImplementationOnce((async (
+ ...args: Parameters<typeof readFile>
+ ) => {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ return readFile(...args);
+ }) as typeof readFile);
+ const opening = projects.getProject("proj_2").then((document) => {
+ editor.document = document;
+ });
+ const result = await mcp.callTool({
+ name: "addTrim",
+ arguments: { ...addTrimArgs, projectId: "proj_2" },
+ });
+ await opening;
+ slowRead.mockRestore();
+ expect(result.isError).toBeFalsy();
+ // The editor holds the project now, so the edit has to be in its copy.
+ expect(editor.applied).toHaveLength(1);
+ expect(editor.document?.timeline.trimRanges).toHaveLength(1);
+ });
+
// 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 () => {
diff --git a/electron/mcp/openscreen-mcp-server.ts b/electron/mcp/openscreen-mcp-server.ts
index 1b0c1d49a..2feb6e084 100644
--- a/electron/mcp/openscreen-mcp-server.ts
+++ b/electron/mcp/openscreen-mcp-server.ts
@@ -90,6 +90,8 @@ export interface McpProjectStore {
): Promise<AxcutDocument | null>;
}
+type ProjectRead = Awaited<ReturnType<McpProjectStore["getProjectForUpdate"]>>;
+
export interface McpToolDeps {
host: McpDocumentHost;
projects: McpProjectStore;
@@ -276,19 +278,10 @@ export function createToolRunner(deps: McpToolDeps) {
/** Any other project: read from and saved to its file. */
async function runOnFile(
projectId: string,
+ read: ProjectRead,
name: string,
args: unknown,
): Promise<CallToolResult> {
- 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(read.document, name, args);
if (execution.document) {
// A restore IS the way back, so it needs no checkpoint of its own.
@@ -322,14 +315,29 @@ export function createToolRunner(deps: McpToolDeps) {
async function run(name: string, rawArgs: unknown): Promise<CallToolResult> {
if (name === LIST_PROJECTS_TOOL) return listProjects();
const { projectId, args } = splitProjectId(rawArgs);
- const snapshot = await deps.host.snapshot();
if (projectId === undefined) {
+ const snapshot = await deps.host.snapshot();
return snapshot ? runOnEditor(snapshot, name, args) : textResult(NO_PROJECT_MESSAGE, true);
}
+ // The file first, the editor second. Reads of a project queue behind each other,
+ // so an editor open of it already under way has returned by now, and the editor
+ // installs what it read before it answers the snapshot: either the snapshot shows
+ // the project, or saveProjectIfUnchanged sees any open that starts after this read.
+ const read = await deps.projects.getProjectForUpdate(projectId).catch((error) => {
+ if (error instanceof DocumentNotFoundError) return null;
+ throw error;
+ });
+ const snapshot = await deps.host.snapshot();
if (snapshot && openProjectId(snapshot) === projectId) {
return runOnEditor(snapshot, name, args);
}
- return runOnFile(projectId, name, args);
+ if (!read) {
+ return textResult(
+ `No project has the id "${projectId}". Call listProjects for the valid ids.`,
+ true,
+ );
+ }
+ return runOnFile(projectId, read, name, args);
}
return (name: string, args: unknown): Promise<CallToolResult> => {