Skip to content

Commit 3ee6a52

Browse files
committed
fix(editor): never save back a project's own file from the open dialog
Opening a project's own file through the dialog (or a drop) read it, then saved that content as the project. An MCP edit landing between the read and the save was overwritten. The dialog now says when the file is a stored project's own file, and the editor loads that project by id instead of saving it back; any other file is imported as before. The parse, migrate and save step the editor's two open paths duplicated now lives in importProjectFile. beforeProjectFileRead goes: with nothing saved back, the dialog's read no longer needs to count against MCP writes.
1 parent fd8e6ce commit 3ee6a52

10 files changed

Lines changed: 146 additions & 87 deletions

File tree

‎electron/ai-edition/document-service.test.ts‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -870,21 +870,6 @@ describe("DocumentService", () => {
870870
expect((await service.getProject(created.project.id)).project.title).toBe("Synced");
871871
});
872872

873-
it("counts the open-file dialog reading the project's own file as a read", async () => {
874-
const created = await service.createProject("Browsed");
875-
const { document, version } = await service.getProjectForUpdate(created.project.id);
876-
await service.beforeProjectFileRead(path.join(tempDir, `${created.project.id}.openscreen`));
877-
expect(await service.saveProjectIfUnchanged(renamed(document, "Edited"), version)).toBeNull();
878-
});
879-
880-
it("ignores the open-file dialog reading a file outside the projects folder", async () => {
881-
const created = await service.createProject("Elsewhere");
882-
const { document, version } = await service.getProjectForUpdate(created.project.id);
883-
await service.beforeProjectFileRead(path.join(mediaDir, `${created.project.id}.openscreen`));
884-
const saved = await service.saveProjectIfUnchanged(renamed(document, "Edited"), version);
885-
expect(saved?.project.title).toBe("Edited");
886-
});
887-
888873
it("writes nothing over a project deleted since", async () => {
889874
const created = await service.createProject("Deleted");
890875
const { document, version } = await service.getProjectForUpdate(created.project.id);
@@ -893,4 +878,19 @@ describe("DocumentService", () => {
893878
await expect(service.getProject(created.project.id)).rejects.toThrow(DocumentNotFoundError);
894879
});
895880
});
881+
882+
describe("storedProjectId", () => {
883+
it("names the project a file in the projects folder is the own file of", () => {
884+
expect(service.storedProjectId(path.join(tempDir, "proj_a.openscreen"))).toBe("proj_a");
885+
expect(service.storedProjectId(path.join(tempDir, "proj_a.axcut"))).toBe("proj_a");
886+
});
887+
888+
it("names nothing for a file anywhere else", () => {
889+
expect(service.storedProjectId(path.join(mediaDir, "proj_a.openscreen"))).toBeUndefined();
890+
expect(
891+
service.storedProjectId(path.join(tempDir, "sub", "proj_a.openscreen")),
892+
).toBeUndefined();
893+
expect(service.storedProjectId(path.join(tempDir, "proj_a.json"))).toBeUndefined();
894+
});
895+
});
896896
});

‎electron/ai-edition/document-service.ts‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -336,21 +336,19 @@ export class DocumentService {
336336
}
337337

338338
/**
339-
* For a read of a project file that bypasses getProject: the open-file dialog,
340-
* which then saves back what it read. If the file is one of this service's
341-
* projects, that counts as a read of it, behind its queued reads and saves, as in
342-
* getProject. Any other file is not this service's business.
339+
* The id of the project `filePath` is the own file of, or undefined for any other
340+
* file. The open-file dialog hands it to the editor, which then loads that project
341+
* instead of saving back the file as read, over any change made since.
343342
*/
344-
async beforeProjectFileRead(filePath: string): Promise<void> {
343+
storedProjectId(filePath: string): string | undefined {
345344
const resolved = path.resolve(filePath);
346-
if (path.relative(path.resolve(this.projectsRoot), path.dirname(resolved)) !== "") return;
345+
if (path.relative(path.resolve(this.projectsRoot), path.dirname(resolved)) !== "") {
346+
return undefined;
347+
}
347348
const extension = [PROJECT_FILE_EXTENSION, LEGACY_PROJECT_FILE_EXTENSION].find((ext) =>
348349
resolved.endsWith(ext),
349350
);
350-
if (!extension) return;
351-
const projectId = path.basename(resolved, extension);
352-
this.touch(projectId);
353-
await this.writeQueues.get(projectId);
351+
return extension ? path.basename(resolved, extension) : undefined;
354352
}
355353

356354
private touch(projectId: string): number {

‎electron/electron-env.d.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ interface Window {
427427
success: boolean;
428428
path?: string;
429429
project?: unknown;
430+
storedProjectId?: string;
430431
message?: string;
431432
canceled?: boolean;
432433
error?: string;
@@ -444,6 +445,7 @@ interface Window {
444445
success: boolean;
445446
path?: string;
446447
project?: unknown;
448+
storedProjectId?: string;
447449
message?: string;
448450
canceled?: boolean;
449451
error?: string;

‎electron/ipc/handlers.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4725,8 +4725,6 @@ export function registerIpcHandlers(
47254725
}
47264726

47274727
const filePath = result.filePaths[0];
4728-
// The editor saves back what it opened here: see beforeProjectFileRead.
4729-
await aiEditionDocuments.beforeProjectFileRead(filePath);
47304728
const content = await fs.readFile(filePath, "utf-8");
47314729
const project = await relinkProjectMedia(JSON.parse(content), DEFAULT_RECORDINGS_DIR);
47324730
currentProjectPath = filePath;
@@ -4745,6 +4743,7 @@ export function registerIpcHandlers(
47454743
success: true,
47464744
path: filePath,
47474745
project,
4746+
storedProjectId: aiEditionDocuments.storedProjectId(filePath),
47484747
};
47494748
} catch (error) {
47504749
console.error("Failed to load project file:", error);
@@ -4773,7 +4772,6 @@ export function registerIpcHandlers(
47734772
if (!stats?.isFile()) {
47744773
return { success: false, message: "File not found" };
47754774
}
4776-
await aiEditionDocuments.beforeProjectFileRead(filePath);
47774775
const content = await fs.readFile(filePath, "utf-8");
47784776
const project = await relinkProjectMedia(JSON.parse(content), DEFAULT_RECORDINGS_DIR);
47794777
currentProjectPath = filePath;
@@ -4803,7 +4801,12 @@ export function registerIpcHandlers(
48034801
);
48044802
}
48054803
setCurrentRecordingSessionState(session);
4806-
return { success: true, path: filePath, project };
4804+
return {
4805+
success: true,
4806+
path: filePath,
4807+
project,
4808+
storedProjectId: aiEditionDocuments.storedProjectId(filePath),
4809+
};
48074810
} catch (error) {
48084811
console.error("Failed to load project file from path:", error);
48094812
return {

‎src/components/ai-edition/EditorEmptyState.tsx‎

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,8 @@ import { AlertCircle, Circle, Film, FolderOpen, Upload, X } from "lucide-react";
1414
import { useCallback, useRef, useState } from "react";
1515
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
1616
import { useScopedT } from "@/contexts/I18nContext";
17-
import {
18-
migrateProjectDataToAxcutDocument,
19-
migrateRawDocumentToCurrent,
20-
} from "@/lib/ai-edition/document/migrate";
21-
import { documentSchema } from "@/lib/ai-edition/schema";
2217
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
23-
import { nativeBridgeClient } from "@/native";
18+
import { importProjectFile } from "./importProjectFile";
2419
import styles from "./NewEditorShell.module.css";
2520

2621
type DropError = "unsupported-format" | "load-failed" | null;
@@ -77,22 +72,11 @@ export function EditorEmptyState({
7772
}
7873
}, [addAsset, ensureProject]);
7974

80-
// A loaded project JSON is either a current AxcutDocument (has its own
81-
// `schemaVersion`) or a legacy EditorProjectData that must be migrated.
82-
// Discriminate on the version field so a current document is never fed to
83-
// the legacy migrator (which reads `.media`/`.editor` and would yield an
84-
// empty doc). Returns true once the project is saved and loaded.
75+
// What the open-file dialog or a drop read: see importProjectFile.
8576
const openLoadedProject = useCallback(
86-
async (raw: unknown): Promise<boolean> => {
87-
const isAxcutDocument =
88-
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
89-
const doc = isAxcutDocument
90-
? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
91-
: migrateProjectDataToAxcutDocument(raw as never);
92-
const saved = await nativeBridgeClient.aiEdition.save(doc);
93-
if (!saved.success || !saved.document) return false;
94-
await loadProject(doc.project.id);
95-
return true;
77+
async (file: { project?: unknown; storedProjectId?: string }) => {
78+
const { projectId } = await importProjectFile(file.project, file.storedProjectId);
79+
await loadProject(projectId);
9680
},
9781
[loadProject],
9882
);
@@ -101,9 +85,7 @@ export function EditorEmptyState({
10185
try {
10286
const result = await window.electronAPI?.loadProjectFile?.();
10387
if (!result?.success || !result.project) return;
104-
if (!(await openLoadedProject(result.project))) {
105-
setDropError("load-failed");
106-
}
88+
await openLoadedProject(result);
10789
} catch {
10890
setDropError("load-failed");
10991
}
@@ -150,9 +132,7 @@ export function EditorEmptyState({
150132
return;
151133
}
152134
try {
153-
if (!(await openLoadedProject(result.project))) {
154-
setDropError("load-failed");
155-
}
135+
await openLoadedProject(result);
156136
} catch {
157137
setDropError("load-failed");
158138
}

‎src/components/ai-edition/NewEditorShell.tsx‎

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22
import { toast } from "sonner";
3-
import type { EditorProjectData } from "@/components/video-editor/projectPersistence";
43
import { toFileUrl } from "@/components/video-editor/projectPersistence";
54
import { useEditorDialogActions } from "@/contexts/EditorDialogsContext";
65
import { useScopedT } from "@/contexts/I18nContext";
@@ -10,10 +9,6 @@ import {
109
computeAudioRowCount,
1110
} from "@/lib/ai-edition/document/audioTracks";
1211
import { createId } from "@/lib/ai-edition/document/ids";
13-
import {
14-
migrateProjectDataToAxcutDocument,
15-
migrateRawDocumentToCurrent,
16-
} from "@/lib/ai-edition/document/migrate";
1712
import {
1813
documentAfterProbedDuration,
1914
PLACEHOLDER_DURATION_SEC,
@@ -25,12 +20,7 @@ import {
2520
setDocumentWordText,
2621
} from "@/lib/ai-edition/document/transcript";
2722
import { isModalOpen } from "@/lib/ai-edition/modalGuard";
28-
import {
29-
type AxcutAudioTrack,
30-
type AxcutClip,
31-
type AxcutDocument,
32-
documentSchema,
33-
} from "@/lib/ai-edition/schema";
23+
import type { AxcutAudioTrack, AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
3424
import { useMcpDocumentHost } from "@/lib/ai-edition/store/mcpDocumentHost";
3525
import { saveWithDeadline, useProjectStore } from "@/lib/ai-edition/store/projectStore";
3626
import {
@@ -59,6 +49,7 @@ import type { AiEditionProjectSummary } from "@/native/contracts";
5949
import { resolveVisibleClips } from "@/native/sceneDescription";
6050
import { useNativePlaybackSync } from "@/native/useNativePlaybackSync";
6151
import { ExportDialog } from "./ExportDialog";
52+
import { importProjectFile } from "./importProjectFile";
6253
import { insertionsEnabled } from "./insertionsEnabled";
6354
import { ChatStripPanel } from "./LeftPanel";
6455
import {
@@ -650,24 +641,9 @@ export function NewEditorShell() {
650641
try {
651642
const result = await window.electronAPI?.loadProjectFile();
652643
if (!result?.success || !result.project) return;
653-
const raw = result.project as unknown;
654-
// A current project file already carries its own `schemaVersion` (v3/v4
655-
// AxcutDocument); an older legacy export is EditorProjectData and must be
656-
// migrated. Discriminate on the version field so a current document is
657-
// never fed to the legacy migrator (which reads `.media`/`.editor` and
658-
// would yield an empty doc).
659-
const isAxcutDocument =
660-
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
661-
const doc = isAxcutDocument
662-
? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
663-
: migrateProjectDataToAxcutDocument(raw as EditorProjectData);
664-
const saved = await nativeBridgeClient.aiEdition.save(doc);
665-
if (saved.success && saved.document) {
666-
await loadProject(doc.project.id);
667-
toast.success(isAxcutDocument ? "Project opened" : "Legacy project migrated and loaded");
668-
} else {
669-
toast.error(saved.error ?? "Failed to open project");
670-
}
644+
const { projectId, legacy } = await importProjectFile(result.project, result.storedProjectId);
645+
await loadProject(projectId);
646+
toast.success(legacy ? "Legacy project migrated and loaded" : "Project opened");
671647
} catch (err) {
672648
toast.error("Could not load project", {
673649
description: err instanceof Error ? err.message : String(err),
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema";
6+
import { DocumentService } from "../../../electron/ai-edition/document-service";
7+
import { importProjectFile } from "./importProjectFile";
8+
9+
// The bridge's save is the main process's: the real DocumentService, on a temp folder.
10+
const bridge = vi.hoisted(() => ({ save: vi.fn() }));
11+
vi.mock("@/native", () => ({ nativeBridgeClient: { aiEdition: bridge } }));
12+
13+
describe("importProjectFile", () => {
14+
let projectsDir: string;
15+
let otherDir: string;
16+
let service: DocumentService;
17+
18+
beforeEach(async () => {
19+
projectsDir = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-projects-"));
20+
otherDir = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-elsewhere-"));
21+
service = new DocumentService(projectsDir, otherDir);
22+
bridge.save.mockImplementation(async (doc: AxcutDocument) => ({
23+
success: true,
24+
document: await service.saveProject(doc),
25+
}));
26+
});
27+
28+
afterEach(async () => {
29+
await fs.rm(projectsDir, { recursive: true, force: true });
30+
await fs.rm(otherDir, { recursive: true, force: true });
31+
});
32+
33+
it("keeps an MCP edit made between the dialog reading a project's own file and opening it", async () => {
34+
const created = await service.createProject("As read");
35+
const file = path.join(projectsDir, `${created.project.id}.openscreen`);
36+
const read: unknown = JSON.parse(await fs.readFile(file, "utf8"));
37+
38+
const { document, version } = await service.getProjectForUpdate(created.project.id);
39+
const edited = { ...document, project: { ...document.project, title: "Edited over MCP" } };
40+
expect(await service.saveProjectIfUnchanged(edited, version)).not.toBeNull();
41+
42+
const { projectId } = await importProjectFile(read, service.storedProjectId(file));
43+
44+
expect(projectId).toBe(created.project.id);
45+
expect((await service.getProject(projectId)).project.title).toBe("Edited over MCP");
46+
});
47+
48+
it("saves a file from outside the projects folder as a project", async () => {
49+
const doc = createEmptyDocument({ projectId: "proj_imported", title: "Imported" });
50+
const file = path.join(otherDir, "proj_imported.openscreen");
51+
52+
const { projectId } = await importProjectFile(doc, service.storedProjectId(file));
53+
54+
expect((await service.getProject(projectId)).project.title).toBe("Imported");
55+
});
56+
});
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// What the open-file dialog (or a drop) read, turned into a project the editor can load.
2+
3+
import type { EditorProjectData } from "@/components/video-editor/projectPersistence";
4+
import {
5+
migrateProjectDataToAxcutDocument,
6+
migrateRawDocumentToCurrent,
7+
} from "@/lib/ai-edition/document/migrate";
8+
import { documentSchema } from "@/lib/ai-edition/schema";
9+
import { nativeBridgeClient } from "@/native";
10+
11+
/**
12+
* Saves `raw` as a project and returns its id, for the caller to load.
13+
*
14+
* A current project file carries its own `schemaVersion` (an AxcutDocument) and is upgraded;
15+
* anything else is a legacy EditorProjectData and is migrated. Discriminate on the version
16+
* field so a current document is never fed to the legacy migrator (which reads
17+
* `.media`/`.editor` and would yield an empty doc).
18+
*
19+
* A project's own file (`storedProjectId`) is not saved: saving it back would write the file
20+
* as read over any change made since, an MCP edit included. Loading it by id reads it again,
21+
* as opening it from the project list does.
22+
*/
23+
export async function importProjectFile(
24+
raw: unknown,
25+
storedProjectId?: string,
26+
): Promise<{ projectId: string; legacy: boolean }> {
27+
const legacy = !(
28+
typeof raw === "object" &&
29+
raw !== null &&
30+
"schemaVersion" in raw &&
31+
"timeline" in raw
32+
);
33+
const doc = legacy
34+
? migrateProjectDataToAxcutDocument(raw as EditorProjectData)
35+
: documentSchema.parse(migrateRawDocumentToCurrent(raw)); // disk-load: upgrade, then validate
36+
if (doc.project.id !== storedProjectId) {
37+
const saved = await nativeBridgeClient.aiEdition.save(doc);
38+
if (!saved.success || !saved.document) {
39+
throw new Error(saved.error ?? "Failed to open project");
40+
}
41+
}
42+
return { projectId: doc.project.id, legacy };
43+
}

‎src/native/contracts.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ export interface ProjectFileResult {
9191
success: boolean;
9292
path?: string;
9393
project?: unknown;
94+
/** Set when the file is a stored project's own file: load that project, never save it back. */
95+
storedProjectId?: string;
9496
message?: string;
9597
canceled?: boolean;
9698
error?: string;

‎technical-documentation/architecture/mcp-server.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ A call naming a project reads its file **before** asking the editor for a snapsh
5656

5757
There is no revision to guard the file with, so the save is refused with "NOT applied … re-read, then retry" when, since the call's read:
5858

59-
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 open-file dialog's direct read of a project file included (`beforeProjectFileRead`). The client's retry, with the same `projectId`, then goes through the editor.
59+
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. The open-file dialog never saves back a project's own file: it loads that project by id (`storedProjectId`), a read like any other.
6060
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.
6161

6262
The check runs inside the project's queue, so nothing in the app reads or saves the project between the check and the write.
@@ -100,5 +100,4 @@ codex mcp add openscreen --url http://127.0.0.1:47821/mcp --bearer-token-env-var
100100
- **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.
101101
- **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.
102102
- **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.
103-
- **The open-file dialog saves back what it read.** Opening a project's own file through it reads the file, then saves that content as the project. An MCP edit landing between the read and that save is overwritten, as any other change would be. Closing it is the dialog's job (not saving back a file that already is the project), not the server's.
104103
- **No project management.** Projects can be listed, read and edited, not created, renamed or deleted.

0 commit comments

Comments
 (0)