Movie Engine 如何讓 AI 智能體修改仍在 Kdenlive 開啟的專案
Two editors, one file: how an AI agent edits a project the user has open
Movie Engine 透過專案鎖、先儲存用戶未儲存的修改、寫入前核對檔案雜湊及確認重載,讓 AI 智能體修改用戶仍在 Kdenlive 開啟的專案。作者亦修正 XmlDocument 未保留空白令命令列預覽中的標題消失,CLI 測試目前 134/134 項通過。小型專案即時更新通過 13/13 項檢查;大型專案(約 1000 個片段)的相關修正尚未重測。
Part 6 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: 1, overview, 2, UI Automation without stealing focus, 3, menu names from translation files, 4, rendering what Kdenlive can't, 5, captions timed to the spoken word.
Here is the situation Movie Engine is built for. Kdenlive is open with a project. I am trimming clips in it. At the same time an AI agent (Claude Code or Codex) is adding a title card to the same project, by editing the .kdenlive file on disk, because Kdenlive on Windows has no automation API. Two writers, one file, and one of them is a GUI that keeps its own copy in memory.
The goal is simple to state: the user's edits are never lost, and the AI's edits always show up in the open editor. This post is the protocol that gets there, and a one-line XML bug that made titles disappear.
The cycle
Every editing command of the project CLI (engine\kdp.ps1) runs the same guard:
- Lock. Take a named mutex for this project, so the agent's own commands and the reload never interleave.
- Pull. If Kdenlive has unsaved edits, press its Save button through UI Automation and wait until Save is disabled again. Now the file holds what the user sees.
- Read and remember the hash of the file.
- Edit in memory, validate (the edit is refused if it would make Kdenlive complain on load).
- Re-check right before writing: same hash on disk, and Kdenlive still has no unsaved edits. Otherwise refuse and ask to run again.
- Snapshot the old file for undo, write the new one with a stamp, release the lock.
- Reload the open Kdenlive (File > Revert), which is confirmed, not assumed.
In code, the lock is a mutex named after the long form of the path, so C:\Users\ABCDEF~1\... and the long spelling map to the same lock:
function Enter-KdLock([string]$project, [int]$timeoutSec = 1800) {
$key = [KdPath]::Long($project).ToLowerInvariant()
$md5 = [Security.Cryptography.MD5]::Create()
$name = 'Local\kdp-' + [BitConverter]::ToString($md5.ComputeHash([Text.Encoding]::UTF8.GetBytes($key))).Replace('-', '')
$mutex = New-Object Threading.Mutex($false, $name)
try {
if (-not $mutex.WaitOne($timeoutSec * 1000)) { throw "Another engine operation has held '$project' for over $timeoutSec s." }
} catch [Threading.AbandonedMutexException] { } # the previous holder died; the lock is ours now
return $mutex
}
And the last checks before writing, from kdp.ps1:
if ((Get-KdHash $Project) -ne $d.LoadedHash) { throw 'Not saved: the project file changed while this command ran (the user saved?). Run the command again.' }
if ($window -and (Get-Process -Id $window.ProcessId -ErrorAction SilentlyContinue)) {
$unsaved = Wait-KdUnsaved $window 120
if ($unsaved -ne $false) { throw "Not saved: the user is editing in Kdenlive (or it did not answer). Run the command again; it will take the user's edits first." }
}
Save-KdpSnapshot $Project $assBefore
Save-Kdp $d
Note -ne $false, not -eq $true. Get-KdUnsaved returns $true, $false, or $null when a busy Kdenlive doesn't answer UI Automation. "Cannot answer" must never be read as "no edits".
Writing: stamp first, then replace atomically
Save-Kdp writes to a temp file, hashes it, records the hash as the "last AI write" stamp, and only then swaps the file in:
$hash = Get-KdHash $tmp
# stamp first: the watcher may see the new file immediately
Set-KdWriteStamp $Path $hash
Move-KdpFileInto $tmp $Path
Move-KdpFileInto uses File.Replace (a single step; Move-Item -Force deletes first, so a reader could see no file at all) and retries for a few seconds while Kdenlive or the watcher has the file open.
Every write also keeps a snapshot of the previous file and its subtitle files under .kdp-history\<project>\undo, up to 100. kdp.ps1 undo and redo step through them.
The watcher: who changed the file?
engine\kd-watch.ps1 runs hidden and polls about every 0.7 s: the file hash, and the state of Kdenlive's Save button (edited, clean, closed, or busy). When the hash changes it has to decide who wrote it:
- The AI, if the new hash equals the stamp. Then reload.
- Kdenlive itself, if Save just went from enabled to disabled (within 5 s). The user saved; nothing to do.
- Anyone else while the user has unsaved edits: a conflict. The watcher does not reload, because a reload would throw the user's work away. It keeps the new file aside and logs it:
if ($state -eq 'edited') {
Write-WatchLog "CONFLICT: file changed while Kdenlive has unsaved edits; not reloading. Copy kept: $(Save-ConflictCopy). Run kd-pull.ps1 and re-apply the change."
$lastHash = $h; continue
}
Timing alone was not enough to tell these apart: an AI write a few seconds after the user's save looked just like the save. The stamp fixed that.
A failed reload is retried after 5 and 10 s; after three failures the log says plainly that the open editor still shows the old version.
The reload never discards edits
kd-reload.ps1 exits 0 only when the reload is confirmed (the timeline widget was rebuilt, so its UI Automation runtime id changed). If the user started editing between the check and the click, Kdenlive asks "revert to the last saved version?". The script closes that question with WindowPattern.Close(), which is Cancel, and returns exit 2 ("unsaved edits"). The agent then pulls again and re-applies its change on top. It never presses Yes.
The bug: titles vanished, but only in previews
The CLI can render check frames and short previews with melt, MLT's command-line player. For that it writes a temporary copy of the project with today's absolute paths. One day every title was missing from those frames, while Kdenlive showed them fine.
The copy was made with XmlDocument, which by default does not preserve whitespace. On save it indented an empty element:
<property name="resource"></property>
into an element containing a line break and spaces. For a Kdenlive title producer (kdenlivetitle), resource is a file name. It took that whitespace for a file name and drew nothing. No error anywhere.
The fix is one property:
# PreserveWhitespace: without it Save indents an empty <property name="resource"></property> into a line break,
# and kdenlivetitle takes that whitespace for a file name and draws nothing (titles were missing in frame/preview).
$x = New-Object System.Xml.XmlDocument; $x.PreserveWhitespace = $true; $x.LoadXml($d.Xml.OuterXml)
And because a fix without a test comes back, the CLI test suite got a check named "frame shows titles", which renders a frame through the command line and compares the result. That suite currently passes 134 of 134 checks (docs/proof/clitest.txt).
What is proven and what is not
From docs/kdenlive-proof.md: live update passes 13 of 13 checks on a small project. On a big project (about 1000 clips) the first run failed because the loading window was taken for a blocking dialog; that is fixed but not rerun yet. I'd rather publish the table than claim more.
Takeaways
- Treat the GUI as a second writer: lock, pull its edits, check the hash, write atomically, reload with confirmation.
- Tag your own writes (a hash stamp) instead of guessing from timing.
- On conflict, keep both versions and never pick for the user.
-
XmlDocument.PreserveWhitespace = $truewhen empty elements mean something.
Windows only, Kdenlive 26.08.3, MIT licensed: https://github.com/vladtarrow/movie-engine. To try it, clone the repo and run:
.\setup.cmd
來源:DEV Community · dev.to