Skip to content

Commit 37b373b

Browse files
committed
feat(mcp): rename a project, import and remove its media, create one
setProjectInfo, importMedia and removeMedia run in the tool runner like any edit, so the project open in the editor changes there live, and openscreen mcp forwards them to the running app. createProject is a media tool, empty or from a video, and returns a checkpoint as stopRecording does. Deleting a project stays out on purpose. Part of #1180
1 parent 2382b8e commit 37b373b

10 files changed

Lines changed: 624 additions & 84 deletions

File tree

‎electron/ai-edition/agent-tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,7 +1242,7 @@ export function documentSnapshotForModel(
12421242
timeBaseNote:
12431243
"clips and trims are in source-time seconds; zooms, speedRegions, annotations, cameraFullscreenRegions and audioTracks are in virtual (edited-timeline) seconds: the editor's ruler, where a trim leaves a hole instead of shortening it and a speed region stretches nothing. The exported video's clock skips those holes and plays sped-up spans faster, so it differs from the ruler once there are any.",
12441244
audioNote:
1245-
"audioTracks are imported voiceover / music files laid over the recording. They are clip-anchored like every other region, so they travel with their clip through reorder and trim, and they play at 1x whatever a speed region does to the picture under them. addAudio places an EXISTING asset of kind 'audio'; nothing here can import a file from disk or record one, so if the project has no audio asset, say so rather than inventing an id.",
1245+
"audioTracks are imported voiceover / music files laid over the recording. They are clip-anchored like every other region, so they travel with their clip through reorder and trim, and they play at 1x whatever a speed region does to the picture under them. addAudio places an EXISTING asset of kind 'audio': if the project has none, a file has to be imported first (importMedia, where it is offered), so never invent an id.",
12461246
zoomNote:
12471247
`renderedScale is what the viewer sees (depth is an ordinal, not a factor: ${ZOOM_DEPTH_LEGEND}). ` +
12481248
"When a zoom carries customScale it wins over depth and depthIsOverridden is true — " +
@@ -2975,7 +2975,7 @@ export function executeAgentTool(
29752975
`Unknown asset: ${assetId}.` +
29762976
(available.length
29772977
? ` Imported audio in this project: ${available.map((a) => `${a.id} (${a.label})`).join(", ")}.`
2978-
: " This project has no imported audio; a file can only be imported or recorded from the editor, not from here."),
2978+
: " This project has no imported audio: a file has to be imported into it first (importMedia, where it is offered)."),
29792979
);
29802980
}
29812981
if (asset.kind !== "audio") {

‎electron/ai-edition/deep-agent/service.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ export const TOOL_DESCRIPTIONS: Record<string, string> = {
223223
"Add a camera-fullscreen region over a span of the edited timeline (virtual seconds): the webcam fills the frame for that span. This only does something when the footage under that span comes from an asset with a linked webcam — check assets[].hasCameraTrack (or hasAnyCamera) in getCurrentDocument first. On footage with no camera the call is refused rather than storing a region that would render nothing; say so instead of retrying.",
224224
setCameraFullscreen:
225225
"Move or resize an existing camera-fullscreen region by id (virtual-timeline seconds). Only the fields you pass are changed. Refused if the new span lands on footage with no linked webcam.",
226-
addAudio: `Lay an ALREADY-IMPORTED audio file over the recording across a span of the edited timeline (virtual seconds): a voiceover, or a music bed. assetId must name an asset whose kind is 'audio' — getCurrentDocument lists them; nothing here can import a file from disk or record one, so if there is none, say so instead of guessing an id. Omit endSec to play the whole file from offsetSec. kind picks the lane ('voiceover' or 'music'). offsetSec is where in the FILE playback starts, gainDb its level (0 unchanged, negative ducks it), fadeInMs / fadeOutMs its fades (0 to ${AUDIO_FADE_MAX_MS} ms, default none; a track too short for both shares its span between them). A voiceover-lane track is also what gets transcribed, so the lane is not only cosmetic.`,
226+
addAudio: `Lay an ALREADY-IMPORTED audio file over the recording across a span of the edited timeline (virtual seconds): a voiceover, or a music bed. assetId must name an asset whose kind is 'audio' — getCurrentDocument lists them. If there is none, a file has to be imported first (importMedia, where it is offered): never guess an id. Omit endSec to play the whole file from offsetSec. kind picks the lane ('voiceover' or 'music'). offsetSec is where in the FILE playback starts, gainDb its level (0 unchanged, negative ducks it), fadeInMs / fadeOutMs its fades (0 to ${AUDIO_FADE_MAX_MS} ms, default none; a track too short for both shares its span between them). A voiceover-lane track is also what gets transcribed, so the lane is not only cosmetic.`,
227227
setAudio: `Move, resize, re-level, re-lane, mute, loop, fade or re-point an existing audio track by id (virtual-timeline seconds). Only the fields you pass are changed. Use it to duck a bed under narration (gainDb), to fade it in or out (fadeInMs / fadeOutMs, 0 to ${AUDIO_FADE_MAX_MS} ms), to shift what part of the file plays (offsetSec), or to move it between the voiceover and music lanes (kind). The whole track is edited, not one fragment of it, so a track split across a cut stays one thing.`,
228228
removeTrim:
229229
"Delete a trim range by id — the cut is undone and that span plays/exports again. This is how you 'remove a trim'; never re-add a trim to undo one.",

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

Lines changed: 74 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,75 @@ function isSupportedAudioPath(filePath: string): boolean {
149149
return SUPPORTED_AUDIO_EXTENSIONS.has(ext);
150150
}
151151

152+
/** Why `input` cannot be filed as its kind of asset, or `null` when it can. */
153+
export function unsupportedAssetPath(input: Pick<AddAssetInput, "path" | "kind">): string | null {
154+
if (!input.path) return "Asset path is required.";
155+
if ((input.kind ?? "video") === "audio") {
156+
return isSupportedAudioPath(input.path)
157+
? null
158+
: `Unsupported audio extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_AUDIO_EXTENSIONS].join(", ")})`;
159+
}
160+
return isSupportedVideoPath(input.path)
161+
? null
162+
: `Unsupported video extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_VIDEO_EXTENSIONS].join(", ")})`;
163+
}
164+
165+
/** The kind a media file is imported as, from its extension: audio only when it cannot be a video. */
166+
export function assetKindForPath(filePath: string): "video" | "audio" {
167+
return !isSupportedVideoPath(filePath) && isSupportedAudioPath(filePath) ? "audio" : "video";
168+
}
169+
170+
/** `doc` with `asset` added to its media, as an import adds it. */
171+
export function documentWithAsset(doc: AxcutDocument, asset: AxcutAsset): AxcutDocument {
172+
// An audio import is an overlay, never the thing the timeline is built
173+
// around, so it must not claim the empty primaryAssetId slot — otherwise the
174+
// first file dropped into a fresh project (a BGM track) would become its
175+
// primary asset and the editor would try to lay out clips from a file with
176+
// no video.
177+
const claimsPrimary = asset.kind !== "audio" && !doc.project.primaryAssetId;
178+
return {
179+
...doc,
180+
assets: [...doc.assets, asset],
181+
project: {
182+
...doc.project,
183+
...(claimsPrimary ? { primaryAssetId: asset.id } : {}),
184+
updatedAt: new Date().toISOString(),
185+
},
186+
};
187+
}
188+
189+
/** `doc` without the asset, its clips, trims and audio tracks. */
190+
export function documentWithoutAsset(doc: AxcutDocument, assetId: string): AxcutDocument {
191+
const assets = doc.assets.filter((a) => a.id !== assetId);
192+
// Primary is the thing the timeline is built around, so it must fall to the
193+
// next VIDEO asset — never an audio overlay (issue #350), which can't be
194+
// primary (see addAsset). Falling back to `assets[0]` would hand primary to
195+
// an audio asset when the removed one was the last video.
196+
const primaryAssetId =
197+
doc.project.primaryAssetId === assetId
198+
? (assets.find((a) => a.kind !== "audio")?.id ?? undefined)
199+
: doc.project.primaryAssetId;
200+
const withoutAssetClips = doc.timeline.clips
201+
.filter((clip) => clip.assetId === assetId)
202+
.reduce((current, clip) => removeClip(current, clip.id), doc);
203+
return {
204+
...withoutAssetClips,
205+
assets,
206+
// Drop imported audio tracks that referenced the removed asset — they
207+
// would otherwise dangle, pointing at an asset the document no longer has.
208+
audioTracks: withoutAssetClips.audioTracks.filter((t) => t.assetId !== assetId),
209+
timeline: {
210+
...withoutAssetClips.timeline,
211+
trimRanges: withoutAssetClips.timeline.trimRanges.filter((r) => r.assetId !== assetId),
212+
},
213+
project: {
214+
...withoutAssetClips.project,
215+
primaryAssetId,
216+
updatedAt: new Date().toISOString(),
217+
},
218+
};
219+
}
220+
152221
function safeProjectId(raw: string): string {
153222
// ponytail: project ids are uuid-prefixed strings (e.g. "proj_<uuid>"). Reject
154223
// anything that smells like path traversal before we ever touch the disk.
@@ -532,23 +601,8 @@ export class DocumentService {
532601

533602
async addAsset(projectId: string, input: AddAssetInput): Promise<AxcutDocument> {
534603
const doc = await this.getProject(projectId);
535-
if (!input.path) {
536-
throw new ProjectFileError("Asset path is required.", projectId);
537-
}
538-
const kind = input.kind ?? "video";
539-
if (kind === "audio") {
540-
if (!isSupportedAudioPath(input.path)) {
541-
throw new ProjectFileError(
542-
`Unsupported audio extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_AUDIO_EXTENSIONS].join(", ")})`,
543-
projectId,
544-
);
545-
}
546-
} else if (!isSupportedVideoPath(input.path)) {
547-
throw new ProjectFileError(
548-
`Unsupported video extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_VIDEO_EXTENSIONS].join(", ")})`,
549-
projectId,
550-
);
551-
}
604+
const unsupported = unsupportedAssetPath(input);
605+
if (unsupported) throw new ProjectFileError(unsupported, projectId);
552606
const absolutePath = path.isAbsolute(input.path) ? input.path : path.resolve(input.path);
553607
// P3.1 — capture the file size at import. Non-fatal: a stat failure
554608
// (network drive, permissions) just leaves sizeBytes undefined.
@@ -560,64 +614,21 @@ export class DocumentService {
560614
}
561615
const asset: AxcutAsset = {
562616
id: createId("asset"),
563-
kind,
617+
kind: input.kind ?? "video",
564618
label: input.label?.trim() || path.basename(absolutePath),
565619
originalPath: absolutePath,
566620
sizeBytes,
567621
cameraTrack: null,
568622
};
569-
// An audio import is an overlay, never the thing the timeline is built
570-
// around, so it must not claim the empty primaryAssetId slot — otherwise the
571-
// first file dropped into a fresh project (a BGM track) would become its
572-
// primary asset and the editor would try to lay out clips from a file with
573-
// no video.
574-
const claimsPrimary = kind !== "audio" && !doc.project.primaryAssetId;
575-
const next: AxcutDocument = {
576-
...doc,
577-
assets: [...doc.assets, asset],
578-
project: {
579-
...doc.project,
580-
...(claimsPrimary ? { primaryAssetId: asset.id } : {}),
581-
updatedAt: new Date().toISOString(),
582-
},
583-
};
584-
return this.saveProject(next);
623+
return this.saveProject(documentWithAsset(doc, asset));
585624
}
586625

587626
async removeAsset(projectId: string, assetId: string): Promise<AxcutDocument> {
588627
const doc = await this.getProject(projectId);
589628
if (!doc.assets.some((a) => a.id === assetId)) {
590629
throw new ProjectFileError(`Asset ${assetId} not found in project ${projectId}.`, projectId);
591630
}
592-
const assets = doc.assets.filter((a) => a.id !== assetId);
593-
// Primary is the thing the timeline is built around, so it must fall to the
594-
// next VIDEO asset — never an audio overlay (issue #350), which can't be
595-
// primary (see addAsset). Falling back to `assets[0]` would hand primary to
596-
// an audio asset when the removed one was the last video.
597-
const primaryAssetId =
598-
doc.project.primaryAssetId === assetId
599-
? (assets.find((a) => a.kind !== "audio")?.id ?? undefined)
600-
: doc.project.primaryAssetId;
601-
const withoutAssetClips = doc.timeline.clips
602-
.filter((clip) => clip.assetId === assetId)
603-
.reduce((current, clip) => removeClip(current, clip.id), doc);
604-
const next: AxcutDocument = {
605-
...withoutAssetClips,
606-
assets,
607-
// Drop imported audio tracks that referenced the removed asset — they
608-
// would otherwise dangle, pointing at an asset the document no longer has.
609-
audioTracks: withoutAssetClips.audioTracks.filter((t) => t.assetId !== assetId),
610-
timeline: {
611-
...withoutAssetClips.timeline,
612-
trimRanges: withoutAssetClips.timeline.trimRanges.filter((r) => r.assetId !== assetId),
613-
},
614-
project: {
615-
...withoutAssetClips.project,
616-
primaryAssetId,
617-
updatedAt: new Date().toISOString(),
618-
},
619-
};
620-
return this.saveProject(next);
631+
return this.saveProject(documentWithoutAsset(doc, assetId));
621632
}
622633

623634
/**

‎electron/ipc/handlers.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5060,6 +5060,13 @@ export function registerIpcHandlers(
50605060
cursor: agentCursorTelemetryReader,
50615061
cameraSegmentation: () => loudnessService.probeSegmentation(),
50625062
version: app.getVersion(),
5063+
// importMedia: the editor's own probe, and the grant a picked file gets, so the editor
5064+
// can play a file a client imported into the project it has open.
5065+
openVideo: openVideoInHiddenWindow,
5066+
approveMedia: (filePath) => {
5067+
const media = normalizeVideoSourcePath(filePath);
5068+
if (media && hasAllowedImportMediaExtension(media)) approveFilePath(media);
5069+
},
50635070
};
50645071
// One runner, so one queue and one checkpoint store, for the in-app server and every
50655072
// `openscreen mcp` the app answers through its channel (app-channel.ts, started by main.ts).

‎electron/mcp/app-channel.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
type McpToolDeps,
4646
type McpToolRunner,
4747
} from "./openscreen-mcp-server";
48+
import { PROJECT_EDIT_TOOLS } from "./project-tools";
4849

4950
const DISCOVERY_FILE = "mcp-app.json";
5051
/** Connect, token and MCP handshake: the app answers in milliseconds when it is alive. */
@@ -260,7 +261,7 @@ export async function connectToApp(
260261
function isReadOnly(name: string): boolean {
261262
if (name === LIST_PROJECTS_TOOL) return true;
262263
if (name === "createCheckpoint" || name === "restoreCheckpoint") return false;
263-
return !isMutatingTool(name);
264+
return !isMutatingTool(name) && !PROJECT_EDIT_TOOLS.has(name);
264265
}
265266

266267
/**

‎electron/mcp/media-tools.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,48 @@ describe("recording", () => {
309309
});
310310
});
311311

312+
describe("createProject", () => {
313+
it("creates an empty project the document tools can edit at once", async () => {
314+
const created = await call("createProject", { title: " Blank " });
315+
expect(created.isError).toBeFalsy();
316+
const { projectId, checkpointId } = JSON.parse(textOf(created));
317+
expect(checkpointId).toEqual(expect.any(String));
318+
const document = await documents.getProject(projectId);
319+
expect(document.project.title).toBe("Blank");
320+
expect(document.assets).toEqual([]);
321+
// Its checkpoint lets an edit land on the file straight away.
322+
const renamed = await call("setProjectInfo", { projectId, title: "Named" });
323+
expect(renamed.isError).toBeFalsy();
324+
expect((await documents.getProject(projectId)).project.title).toBe("Named");
325+
});
326+
327+
it("lays a video out as one clip, titled after the file, with the zooms of its clicks", async () => {
328+
await fs.writeFile(videoPath, "video");
329+
const created = await call("createProject", { videoPath });
330+
expect(created.isError).toBeFalsy();
331+
const result = JSON.parse(textOf(created));
332+
expect(result).toMatchObject({ durationSec: 12 });
333+
expect(result.autoZooms).toBeGreaterThan(0);
334+
const document = await documents.getProject(result.projectId);
335+
expect(document.project.title).toBe("take");
336+
expect(document.timeline.clips).toHaveLength(1);
337+
expect(document.assets[0]).toMatchObject({ originalPath: videoPath, durationSec: 12 });
338+
});
339+
340+
it("creates nothing from a path it cannot use", async () => {
341+
const missing = await call("createProject", { videoPath: path.join(dir, "gone.mp4") });
342+
expect(missing.isError).toBe(true);
343+
expect(textOf(missing)).toContain("No file");
344+
const relative = await call("createProject", { videoPath: "take.mp4" });
345+
expect(textOf(relative)).toContain("must be absolute");
346+
await fs.writeFile(videoPath, "video");
347+
openVideoFails = true;
348+
const unreadable = await call("createProject", { videoPath });
349+
expect(textOf(unreadable)).toContain("media error 4");
350+
expect(await documents.listProjects()).toEqual([]);
351+
});
352+
});
353+
312354
describe("pointerSamples", () => {
313355
const startedAt = 10_000;
314356
const samples = pointerSamples(
@@ -716,7 +758,7 @@ describe("the media tools in the app", () => {
716758
allowed = false;
717759
const app = await connectApp();
718760
expect(app.getInstructions()).toContain(
719-
"startRecording and exportVideo are refused too while 'MCP edits'",
761+
"startRecording, exportVideo and createProject are refused too while 'MCP edits'",
720762
);
721763
const started = await callOn(app, "startRecording", {});
722764
expect(started.isError).toBe(true);
@@ -728,6 +770,9 @@ describe("the media tools in the app", () => {
728770
});
729771
expect(textOf(exported)).toContain("'MCP edits'");
730772
expect(runners.started).toEqual([]);
773+
const created = await callOn(app, "createProject", {});
774+
expect(textOf(created)).toContain("'MCP edits'");
775+
expect(await documents.listProjects()).toEqual([]);
731776
// Reading stays open: listing what could be recorded changes nothing.
732777
runners.results.sources = {
733778
success: true,

0 commit comments

Comments
 (0)