<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Movie Engine]]></title><description><![CDATA[Movie Engine]]></description><link>https://movie-engine.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:13:07 GMT</lastBuildDate><atom:link href="https://movie-engine.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[I analyzed my coding agent's logs: where the quota actually goes]]></title><description><![CDATA[I keep hitting usage limits in Claude Code, and for months my answer to "why?" was a guess. The usage tools I tried told me how much I used, not why. So I…]]></description><link>https://movie-engine.hashnode.dev/i-analyzed-my-coding-agent-s-logs-where-the-quota-actually-goes</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/i-analyzed-my-coding-agent-s-logs-where-the-quota-actually-goes</guid><category><![CDATA[AI]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[devtools]]></category><category><![CDATA[claude]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Wed, 02 Dec 2026 14:10:03 GMT</pubDate><content:encoded><![CDATA[<p>I keep hitting usage limits in Claude Code, and for months my answer to "why?" was a guess. The usage tools I tried told me how much I used, not why. So I wrote a log reader, quota-autopsy, and ran it on my own machine. This post is what it found in one week of my own logs, plus how to run it on yours. I am the author of the tool. It is MIT-licensed and free.</p>
<p>One caveat up front: this is one person's week (7 days up to 2026-11-30), not a study. Your numbers will differ. The value is in the method and the categories, not in my totals.</p>
<h2>What I measured</h2>
<p>Claude Code saves a transcript of every session under <code>~/.claude/projects</code>. Each API response in those files carries token counts: fresh input, cache writes, cache reads and output. That is enough to rebuild a cost picture without any network call.</p>
<p>My week: 1,281 log files (12.9 GB), 36,689 requests, 78 sessions. The cache hit rate was 98%, which sounds perfect and is not the whole story, as the rest of this post shows.</p>
<p>Costs here are estimates at API list prices. On a subscription they are not your bill, so I only use them to compare causes against each other. That is also why I quote shares and counts below, not currency.</p>
<p>As a sanity check, I compared the per-session estimates with the cost records Claude Code writes itself. The median ratio was 1.00 over 68 sessions (10th to 90th percentile: 0.88 to 1.13). Good enough to rank causes, not good enough to treat as exact.</p>
<h2>Cause 1: cache misses after idle gaps</h2>
<p>Prompt caching makes a long conversation cheap, as long as the cache is still alive. The cache has a time to live: 5 minutes or 1 hour, depending on the session. If you pause longer than that, the next request re-writes the whole prefix instead of reading it.</p>
<p>I had 192 cache rebuilds. 70 came after a pause longer than the TTL in use. The other 122 had no pause at all. Those are a different problem: the prefix changed, or the model changed, or I switched between fast and standard mode.</p>
<p>The worst single rebuild re-wrote 791K tokens after a 3.1-hour pause, with a 1-hour TTL. That is a single request, and it is the kind of cost that is invisible until something lists it.</p>
<p>What this suggests: resuming a very large session after a long break pays for the whole context again. Starting fresh with a short summary may be cheaper. Check your own report before you decide.</p>
<h2>Cause 2: big tool results that stay in context</h2>
<p>A tool result (a file read, a test log, a web page) goes into the conversation once, but it is sent again with every later request. A 10K-token result read early in a session is paid for on every turn after it.</p>
<p>1,290 tool results of 10K tokens or more stayed in my context. Re-sending them accounted for about 6.6% of my estimate. Not the biggest item, but one of the more avoidable ones: a filtered view of a long log is often enough.</p>
<p>How the tool sizes a result: the API reports how much the next prompt grew, so quota-autopsy uses that number rather than guessing from characters. 98.5% of tool-result sizes were measured this way. For the rest it falls back to a character estimate, which ran 1.26 times too low, so it rescales by the ratio of each thread.</p>
<p>It also flags repeated reads: the same file and range read again with no edit in between.</p>
<h2>Cause 3: subagents</h2>
<p>This was the surprise. 71% of my estimate came from subagent threads (440 of them). When the main agent delegates to a subagent, that subagent runs its own conversation with its own context and its own cache. It is easy to forget that each one is a full set of requests.</p>
<p>I do not conclude that subagents are bad. The log shows what they cost, not whether the work was worth it. But I would not have guessed the share.</p>
<h2>Cause 4: tool and MCP definitions</h2>
<p>Every tool definition, including the ones an MCP server adds, is part of the prompt. A server that exposes many tools makes every request bigger, and a change to the definitions in the middle of a session can change the cache prefix. quota-autopsy reads the definition sizes where Claude Code logs them and lists them as a cause. I have no headline number for this one from my week, so I will not make one up. Check yours: it is quick to see.</p>
<h2>Long context</h2>
<p>23,944 of my requests ran with more than 200K tokens of context. The part of those prompts beyond 200K was about 28% of the estimate. Long context is where several of the causes above stack up: a rebuild after an idle gap costs more the longer the context is, and so does every re-sent tool result.</p>
<h2>How to see it for your own logs</h2>
<p>Everything runs offline and read-only. There is no telemetry. Pick one:</p>
<pre><code>npx -y github:vladtarrow/quota-autopsy
</code></pre>
<p>Windows (PowerShell):</p>
<pre><code>irm https://github.com/vladtarrow/quota-autopsy/releases/latest/download/quota-autopsy-windows-x64.exe -OutFile quota-autopsy.exe
.\quota-autopsy.exe
</code></pre>
<p>macOS and Linux (x64 or arm64):</p>
<pre><code>curl -fsSLo quota-autopsy https://github.com/vladtarrow/quota-autopsy/releases/latest/download/quota-autopsy-$(uname -s | tr A-Z a-z)-$(uname -m | sed 's/x86_64/x64/;s/aarch64/arm64/')
chmod +x quota-autopsy &amp;&amp; ./quota-autopsy
</code></pre>
<p>Useful flags:</p>
<pre><code>quota-autopsy --demo                  # full report on synthetic logs, if you have no logs yet
quota-autopsy --since 24h             # time window; default is 7d; also 30d, 2026-11-01, all
quota-autopsy --html report.html      # one self-contained HTML page
quota-autopsy --json &gt; report.json    # machine-readable output
quota-autopsy --redact --html a.html  # hide projects, paths and commands before sharing
quota-autopsy --verbose               # add the log file and line for every finding
</code></pre>
<p>The report is a "why it burned" list of causes. Each finding has the session id and the time, so you can go back and look. A cache miss from an idle gap reads like "idle 12m &gt; 5m TTL". A rebuild with no pause is labelled as such. On my 12.9 GB week the compiled binary took 74 seconds, with other work running on the machine. Expect a minute or more on a large history.</p>
<h2>What it cannot tell you</h2>
<ul>
<li>It cannot see server-side limits. If your quota shrank on the provider's side, no local log shows that. It only shows where your requests went.</li>
<li>Dollar figures are list-price estimates. On a subscription, compare causes with each other.</li>
<li>Some things are not in the logs and are not counted: the separate search request behind each WebSearch call (estimated and shown as a note), compaction summary calls and title generation.</li>
<li><code>--redact</code> hides projects, paths and commands, but keeps host names, model names and numbers. Read a report before you share it.</li>
<li>Codex CLI support is experimental. I tested it on 13 Codex Desktop rollouts only. Gemini CLI and OpenCode are planned, not supported.</li>
</ul>
<h2>What I would do with this</h2>
<p>Three things I plan to look at after this week: resuming an expired giant context after a break, dumping long logs into the conversation, and what I delegate to subagents. None of that is clever. It just needed a list of causes with timestamps, instead of a total.</p>
<p>If you run it and find a cause I have missed, or a log shape it misreads, please open an issue (a <code>--redact</code> report helps): <a href="https://github.com/vladtarrow/quota-autopsy">https://github.com/vladtarrow/quota-autopsy</a></p>
]]></content:encoded></item><item><title><![CDATA[Two editors, one file: how an AI agent edits a project the user has open]]></title><description><![CDATA[Also published on DEV. Part 6 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: 1…]]></description><link>https://movie-engine.hashnode.dev/two-editors-one-file-how-an-ai-agent-edits-a-project-the-user-has-open</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/two-editors-one-file-how-an-ai-agent-edits-a-project-the-user-has-open</guid><category><![CDATA[Powershell]]></category><category><![CDATA[xml]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[video]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Wed, 25 Nov 2026 10:59:27 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/two-editors-one-file-how-an-ai-agent-edits-a-project-the-user-has-open-1cdm">DEV</a>.</em></p>
<p><em>Part 6 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">1, overview</a>, <a href="https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4">2, UI Automation without stealing focus</a>, <a href="https://dev.to/vladtarrow/finding-menu-items-in-31-languages-by-reading-the-apps-own-translation-files-l2c">3, menu names from translation files</a>, <a href="https://dev.to/vladtarrow/motion-graphics-an-editor-cant-do-render-them-with-headless-edge-place-them-as-clips-1b21">4, rendering what Kdenlive can't</a>, <a href="https://dev.to/vladtarrow/timing-captions-to-the-spoken-word-with-edge-tts-word-boundaries-e33">5, captions timed to the spoken word</a>.</em></p>
<p>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 <code>.kdenlive</code> 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.</p>
<p>The goal is simple to state: <strong>the user's edits are never lost, and the AI's edits always show up in the open editor.</strong> This post is the protocol that gets there, and a one-line XML bug that made titles disappear.</p>
<h2>The cycle</h2>
<p>Every editing command of the project CLI (<code>engine\kdp.ps1</code>) runs the same guard:</p>
<ol>
<li><strong>Lock.</strong> Take a named mutex for this project, so the agent's own commands and the reload never interleave.</li>
<li><strong>Pull.</strong> 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.</li>
<li><strong>Read and remember the hash</strong> of the file.</li>
<li><strong>Edit</strong> in memory, validate (the edit is refused if it would make Kdenlive complain on load).</li>
<li><strong>Re-check</strong> right before writing: same hash on disk, and Kdenlive still has no unsaved edits. Otherwise refuse and ask to run again.</li>
<li><strong>Snapshot</strong> the old file for undo, <strong>write</strong> the new one with a stamp, release the lock.</li>
<li><strong>Reload</strong> the open Kdenlive (File &gt; Revert), which is confirmed, not assumed.</li>
</ol>
<p>In code, the lock is a mutex named after the long form of the path, so <code>C:\Users\ABCDEF~1\...</code> and the long spelling map to the same lock:</p>
<pre><code class="language-powershell">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
}
</code></pre>
<p>And the last checks before writing, from <code>kdp.ps1</code>:</p>
<pre><code class="language-powershell">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
</code></pre>
<p>Note <code>-ne $false</code>, not <code>-eq $true</code>. <code>Get-KdUnsaved</code> returns <code>$true</code>, <code>$false</code>, or <code>$null</code> when a busy Kdenlive doesn't answer UI Automation. "Cannot answer" must never be read as "no edits".</p>
<h2>Writing: stamp first, then replace atomically</h2>
<p><code>Save-Kdp</code> writes to a temp file, hashes it, records the hash as the "last AI write" stamp, and only then swaps the file in:</p>
<pre><code class="language-powershell">$hash = Get-KdHash $tmp
# stamp first: the watcher may see the new file immediately
Set-KdWriteStamp $Path $hash
Move-KdpFileInto $tmp $Path
</code></pre>
<p><code>Move-KdpFileInto</code> uses <code>File.Replace</code> (a single step; <code>Move-Item -Force</code> 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.</p>
<p>Every write also keeps a snapshot of the previous file and its subtitle files under <code>.kdp-history\&lt;project&gt;\undo</code>, up to 100. <code>kdp.ps1 undo</code> and <code>redo</code> step through them.</p>
<h2>The watcher: who changed the file?</h2>
<p><code>engine\kd-watch.ps1</code> runs hidden and polls about every 0.7 s: the file hash, and the state of Kdenlive's Save button (<code>edited</code>, <code>clean</code>, <code>closed</code>, or <code>busy</code>). When the hash changes it has to decide who wrote it:</p>
<ul>
<li><strong>The AI</strong>, if the new hash equals the stamp. Then reload.</li>
<li><strong>Kdenlive itself</strong>, if Save just went from enabled to disabled (within 5 s). The user saved; nothing to do.</li>
<li><strong>Anyone else while the user has unsaved edits</strong>: a conflict. The watcher does <em>not</em> reload, because a reload would throw the user's work away. It keeps the new file aside and logs it:</li>
</ul>
<pre><code class="language-powershell">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
}
</code></pre>
<p>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.</p>
<p>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.</p>
<h2>The reload never discards edits</h2>
<p><code>kd-reload.ps1</code> exits 0 only when the reload is <strong>confirmed</strong> (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 <code>WindowPattern.Close()</code>, 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.</p>
<h2>The bug: titles vanished, but only in previews</h2>
<p>The CLI can render check frames and short previews with <code>melt</code>, 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.</p>
<p>The copy was made with <code>XmlDocument</code>, which by default does not preserve whitespace. On save it indented an empty element:</p>
<pre><code class="language-xml">&lt;property name="resource"&gt;&lt;/property&gt;
</code></pre>
<p>into an element containing a line break and spaces. For a Kdenlive title producer (<code>kdenlivetitle</code>), <code>resource</code> is a file name. It took that whitespace for a file name and drew nothing. No error anywhere.</p>
<p>The fix is one property:</p>
<pre><code class="language-powershell"># PreserveWhitespace: without it Save indents an empty &lt;property name="resource"&gt;&lt;/property&gt; 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)
</code></pre>
<p>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 (<code>docs/proof/clitest.txt</code>).</p>
<h2>What is proven and what is not</h2>
<p>From <code>docs/kdenlive-proof.md</code>: 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.</p>
<h2>Takeaways</h2>
<ul>
<li>Treat the GUI as a second writer: lock, pull its edits, check the hash, write atomically, reload with confirmation.</li>
<li>Tag your own writes (a hash stamp) instead of guessing from timing.</li>
<li>On conflict, keep both versions and never pick for the user.</li>
<li><code>XmlDocument.PreserveWhitespace = $true</code> when empty elements mean something.</li>
</ul>
<p>Windows only, Kdenlive 26.08.3, MIT licensed: <strong><a href="https://github.com/vladtarrow/movie-engine">https://github.com/vladtarrow/movie-engine</a></strong>. To try it, clone the repo and run:</p>
<pre><code class="language-powershell">.\setup.cmd
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Timing captions to the spoken word with Edge TTS word boundaries]]></title><description><![CDATA[Also published on DEV. Part 5 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: 1…]]></description><link>https://movie-engine.hashnode.dev/timing-captions-to-the-spoken-word-with-edge-tts-word-boundaries</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/timing-captions-to-the-spoken-word-with-edge-tts-word-boundaries</guid><category><![CDATA[Node.js]]></category><category><![CDATA[tts]]></category><category><![CDATA[video]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Tue, 24 Nov 2026 15:18:01 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/timing-captions-to-the-spoken-word-with-edge-tts-word-boundaries-e33">DEV</a>.</em></p>
<p><em>Part 5 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">1, overview</a>, <a href="https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4">2, UI Automation without stealing focus</a>, <a href="https://dev.to/vladtarrow/finding-menu-items-in-31-languages-by-reading-the-apps-own-translation-files-l2c">3, menu names from translation files</a>, <a href="https://dev.to/vladtarrow/motion-graphics-an-editor-cant-do-render-them-with-headless-edge-place-them-as-clips-1b21">4, rendering what Kdenlive can't</a>.</em></p>
<p>In explainer videos and shorts, the thing that makes captions feel "pro" is timing: a word pops up on screen at the moment the narrator says it, a highlight box grows under "stand out" exactly on "stand out", the cursor clicks on "after". Doing that by hand means scrubbing audio and nudging keyframes for hours.</p>
<p>Movie Engine gets those times for free from the voice-over itself. This post shows the pipeline: Edge TTS with word boundaries, a small <code>voice.json</code> file, and generators that read it.</p>
<h2>One mp3 per line, plus word timings</h2>
<p><code>engine/voice/voice.mjs</code> uses the <code>msedge-tts</code> package, which talks to the same speech service as Microsoft Edge's read-aloud feature. No API key is needed. The input is a list of lines:</p>
<pre><code class="language-json">[{ "id": "037", "text": "The key is to make your brand stand out." }]
</code></pre>
<p>Every line becomes its own mp3. That is a deliberate choice for editing: on the timeline each line is a separate clip, so the agent (or you) can move a line, cut between lines, or re-voice one without touching the others.</p>
<p>The important flag is <code>wordBoundaryEnabled</code>. With it, the service sends metadata events alongside the audio:</p>
<pre><code class="language-js">await tts.setMetadata(VOICE, OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3, { wordBoundaryEnabled: true });
</code></pre>
<p>The offsets come in 100-nanosecond ticks, so dividing by 10^7 gives seconds:</p>
<pre><code class="language-js">const words = JSON.parse(fs.readFileSync(meta, "utf8")).Metadata
  .filter((m) =&gt; m.Type === "WordBoundary")
  .map((m) =&gt; ({
    text: m.Data.text.Text,
    start: +(m.Data.Offset / 1e7).toFixed(3),
    end: +((m.Data.Offset + m.Data.Duration) / 1e7).toFixed(3),
  }));
</code></pre>
<p>The real duration of each mp3 is measured with the <code>ffprobe.exe</code> that ships with Kdenlive, and everything lands in one file:</p>
<pre><code class="language-json">[{ "id": "037", "text": "The key is to make your brand stand out.", "file": "037.mp3",
   "duration": 2.904,
   "words": [{ "text": "The", "start": 0.1, "end": 0.212 }, { "text": "key", "start": 0.225, "end": 0.45 }, ...] }]
</code></pre>
<p>(Numbers here are illustrative; the shape is exactly what <code>voice.mjs</code> writes.)</p>
<h2>Cache per line, keyed by voice, rate and text</h2>
<p>Scripts change. When I fix three lines out of eighty, I don't want eighty requests and eighty slightly different takes. Each line is cached under a hash of everything that affects the sound:</p>
<pre><code class="language-js">const key = crypto.createHash("sha1").update(`${VOICE}|${RATE}|${text}`).digest("hex").slice(0, 16);
const dir = path.join(OUT, ".cache", key);
if (fs.existsSync(audio) &amp;&amp; fs.existsSync(meta)) reused++;
else ({ audioFilePath: audio, metadataFilePath: meta } = await synthesize(text, dir));
</code></pre>
<p>Changing the voice (<code>ru-RU-DmitryNeural</code>) or the rate (<code>+10%</code>) naturally invalidates everything; editing one line re-voices only that line. The run ends with a summary like <code>80 lines (77 from cache), 312.4 s of speech</code>.</p>
<h2>The bug: one ampersand killed the stream</h2>
<p>A line like "Terri &amp; Sandy" failed every time with <em>Stream closed before the synthesis completed</em>. Nothing about the error points at the text.</p>
<p>The cause: <code>msedge-tts</code> puts your text into SSML <strong>unescaped</strong>. SSML is XML, a bare <code>&amp;</code> makes the document invalid, and the service just closes the connection. The fix is three replacements before the text goes in:</p>
<pre><code class="language-js">// msedge-tts sends the text inside SSML unescaped: a bare "&amp;" (e.g. "Terri &amp; Sandy") kills the stream
const ssml = text.replace(/&amp;/g, "&amp;amp;").replace(/&lt;/g, "&amp;lt;").replace(/&gt;/g, "&amp;gt;");
return await tts.toFile(dir, ssml, { rate: RATE });
</code></pre>
<p>The service also drops connections now and then for no visible reason, so <code>synthesize</code> retries up to four times with a growing pause (1.5 s, 3 s, 4.5 s) and creates a fresh client each attempt.</p>
<h2>Using the timings: kinetic text</h2>
<p><code>engine/tools/kinetic-text.ps1</code> renders per-letter animated captions (letters rise, scale up with a slight overshoot and fade in one after another) to transparent <code>.mov</code> clips. Its input names the first frame of each word:</p>
<pre><code class="language-json">[{ "n": 234, "L": 139, "lines": ["The key is to make", "your brand stand out"],
   "hl": "stand out", "starts": [2, 4, 13, ...] }]
</code></pre>
<p><code>starts</code> is just the word times from <code>voice.json</code> converted to frames relative to the card, roughly <code>round((word.start - cardStart) * fps)</code>. Each letter of a word starts a frame after the previous one, and the highlight box starts two frames after its first word:</p>
<pre><code class="language-powershell">[void]$letters.Add([pscustomobject]@{ ch = $w[$k]; ...; start = $ws + $k })
...
$hlBoxes += [pscustomobject]@{ x = $wx - 0.2 * $size; ...; start = $ws + 2 }
</code></pre>
<p>Because the captions are baked into video, the <code>cards.json</code> is kept with the project and the output goes to <code>materials/aigenerated/&lt;project&gt;/</code>. Change a word or the voice, re-run, and the clip on the timeline is replaced with a new version (files are never overwritten).</p>
<h2>Using the timings: actions in a film</h2>
<p>For long explainer films (<code>engine/tools/film-render.mjs</code>), the direction is one line per shot and any action can be pinned to a word with <code>@word</code>:</p>
<pre><code>3 | click 116 108 @before | click 268 108 @after | chips Before~After @after
</code></pre>
<p>The film kit flattens all words of all lines into one list and, for each <code>@word</code>, takes the first matching word that starts inside the shot (allowing 0.6 s of lead-in):</p>
<pre><code class="language-js">function wordTime (shot, word, report = true) {
  const key = norm(word)
  for (const w of words) {
    if (w.a &lt; shot.t0 - 0.6) continue
    if (w.a &gt; shot.t1) break
    if (w.w.startsWith(key)) return Math.max(shot.t0 + 0.05, w.a)
  }
  if (report) problems.push(`shot ${shot.n}: the voice does not say "${word}" during it`)
  return null
}
</code></pre>
<p>Matching is by prefix of a normalised word, so <code>@brand</code> also matches "brand's". When a word is missing, <code>film-render.mjs --check</code> reports it before any rendering starts, a typical error after a script edit: the line changed, the direction still refers to the old wording.</p>
<h2>Why this matters for an AI editor</h2>
<p>An agent can't "listen" to the cut. With word timings in a file, it doesn't need to: every timing decision is a lookup, every caption and click lands on the spoken word, and when the script changes the whole chain is re-generated in minutes. Speech recognition for footage you recorded yourself (Whisper or Vosk) is not included yet, because it needs a separate download.</p>
<p>Windows only, Kdenlive 26.08.3, MIT licensed: <strong><a href="https://github.com/vladtarrow/movie-engine">https://github.com/vladtarrow/movie-engine</a></strong>. To try it, clone the repo and run:</p>
<pre><code class="language-powershell">.\setup.cmd
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Motion graphics an editor can't do: render them with headless Edge, place them as clips]]></title><description><![CDATA[Also published on DEV. Part 4 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: 1…]]></description><link>https://movie-engine.hashnode.dev/motion-graphics-an-editor-can-t-do-render-them-with-headless-edge-place-them-as-clips</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/motion-graphics-an-editor-can-t-do-render-them-with-headless-edge-place-them-as-clips</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[canvas]]></category><category><![CDATA[FFmpeg]]></category><category><![CDATA[video]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Tue, 24 Nov 2026 07:16:37 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/motion-graphics-an-editor-cant-do-render-them-with-headless-edge-place-them-as-clips-1b21">DEV</a>.</em></p>
<p><em>Part 4 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">1, overview</a>, <a href="https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4">2, UI Automation without stealing focus</a>, <a href="https://dev.to/vladtarrow/finding-menu-items-in-31-languages-by-reading-the-apps-own-translation-files-l2c">3, menu names from translation files</a>.</em></p>
<p>Kdenlive is a good editor, but its engine (MLT) has no per-letter text animation, no expressions, little 3D, and heavy effects slow playback down. When an AI agent is building the cut, the temptation is to quietly use a weaker effect. Movie Engine has a rule against that: <strong>whatever Kdenlive can't do is generated by code outside, then placed on the timeline as an ordinary clip.</strong> The user still sees and trims it in Kdenlive like any other clip.</p>
<p>This post walks through the three generator styles in the repo and the plumbing they share.</p>
<h2>The contract: a scene is a pure function of time</h2>
<p><code>engine/tools/html-render.mjs</code> renders any HTML/CSS/canvas page to video. The page defines three things:</p>
<pre><code class="language-js">window.SCENE = { fps: 30, frames: 90, width: 1920, height: 1080 }
window.ready = /* a promise: fonts and images loaded */
window.render = t =&gt; { /* draw the moment t (seconds) */ }
</code></pre>
<p>Because <code>render(t)</code> depends on nothing but <code>t</code>, any frame can be drawn on its own, out of order, in a separate browser. That is what makes parallel rendering and motion blur trivial. The demo in <code>examples/demo/scene/scene.html</code> is a title card with a 3D flip, a cursor and a click ripple:</p>
<pre><code class="language-js">window.render = t =&gt; {
  const flip = out(span(t, 0.1, 0.9))
  const press = span(t, CLICK, 0.12) - span(t, CLICK + 0.12, 0.3)
  $('card').style.transform =
    `rotateX(${lerp(-80, 0, flip)}deg) scale(${lerp(0.8, 1, back(span(t, 0.1, 0.9))) - 0.04 * press})`
  $('card').style.opacity = flip
  // ...cursor path and ripple
}
</code></pre>
<h2>Headless Edge, no network, no window</h2>
<p>Every Windows 10/11 machine has Microsoft Edge, so the renderer drives it over the DevTools protocol instead of shipping Chromium. It starts Edge headless with a throw-away profile and a resolver rule that maps every host to nothing, so a scene can only load local files:</p>
<pre><code class="language-js">spawn(findBrowser(), [
  '--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`,
  '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1',
  '--allow-file-access-from-files',
  '--force-color-profile=srgb', '--force-device-scale-factor=1', '--hide-scrollbars',
  'about:blank'
], { stdio: 'ignore', windowsHide: true })
</code></pre>
<p><code>--remote-debugging-port=0</code> picks a free port, which Edge writes to <code>DevToolsActivePort</code> in the profile; the script reads it and connects with a plain WebSocket. The browser runs at below-normal priority, because the user is working on the same PC.</p>
<h2>Motion blur by sub-frame sampling</h2>
<p>Each output frame is the average of 16 renders spread over half a frame interval (a 180° shutter, centred on the frame):</p>
<pre><code class="language-js">for (let s = 0; s &lt; sub; s++) {
  const offset = sub &gt; 1 ? ((s + 0.5) / sub - 0.5) / 2 : 0
  ffmpeg.stdin.write(await shoot(Math.max(0, f + offset) / scene.fps))
}
</code></pre>
<p>The PNG screenshots are piped into the bundled ffmpeg at <code>fps × 16</code>, and ffmpeg does the averaging and the decimation:</p>
<pre><code class="language-js">filters.push(`tmix=frames=${sub}`, `select='eq(mod(n\\,${sub})\\,${sub - 1})'`, `setpts=N/(${scene.fps}*TB)`)
</code></pre>
<p>Output is H.264 at CRF 12 with a 15-frame GOP, so the editor can seek quickly. The default <code>--sub 16</code> is not arbitrary: with 4 samples a fast move shows visible steps. With <code>--workers 5</code> the frame range is split between several Edge processes and the parts are joined with ffmpeg's concat demuxer without re-encoding. <code>--frames 0,45</code> renders only check stills, which is what the agent looks at before spending minutes on a full render.</p>
<h2>Long films: compose on the GPU, encode in the page</h2>
<p>Screenshots are fine for a 3-second card, and slow for a 3-minute explainer. <code>engine/tools/film-render.mjs</code> with <code>engine/tools/film/film-kit.js</code> keeps everything inside the page: frames are drawn on an <code>OffscreenCanvas</code>, the motion-blur samples are accumulated into a canvas with 16-bit float colour, and WebCodecs encodes H.264 right there. Only finished video leaves the browser.</p>
<pre><code class="language-js">const sum = new OffscreenCanvas(W, H)
const sg = sum.getContext('2d', { colorType: 'float16' })
// for sample k of count: draw the foreground at time t + offset, then
sg.globalAlpha = 1 / (k + 1)     // running average
sg.drawImage(layer, 0, 0)
</code></pre>
<p>The number of samples is adaptive. A "dry pass" draws the frame at t ± a quarter frame without painting, collects the positions of everything that moves, and picks enough samples that neighbouring samples are at most 2.5 px apart (1 to 56). A still shot costs one sample; a whip pan gets many. The docs give about 45 frames/s on a mid-range GPU, roughly 20 times faster than the screenshot path.</p>
<p>Films are written as data plus one line of direction per shot, with actions timed to the voice-over (<code>@word</code> fires when the voice says that word; that is the topic of the next post):</p>
<pre><code>1 | hover 192 108 @brand | tag 300 60 Your brand @deserves | confetti 192 90 @film
3 | click 116 108 @before | click 268 108 @after | chips Before~After @after
</code></pre>
<p><code>--check</code> lists direction errors (an unknown action, a word the voice never says during that shot) and <code>--shots all</code> renders a still of every shot to review before the real render.</p>
<h2>Overlays need alpha</h2>
<p>A full-frame scene can be an mp4. Text and annotations that sit <em>over</em> footage need transparency. <code>engine/tools/kinetic-text.ps1</code> (per-letter kinetic captions) and <code>annotate.ps1</code> (hand-drawn circles, arrows, underlines that draw on) draw frames with <code>System.Drawing</code> into 32-bit ARGB bitmaps and encode a PNG-codec QuickTime file, which keeps the alpha channel:</p>
<pre><code class="language-powershell">&amp; $ff -hide_banner -loglevel error -y -framerate $Fps -i (Join-Path $tmp 'f%04d.png') -c:v png -pix_fmt rgba $out
</code></pre>
<p>The font is loaded from <code>engine/fonts/Poppins-Bold.ttf</code> with a <code>PrivateFontCollection</code>, so nothing is installed into Windows and the folder stays portable. One PowerShell trap worth knowing for animation code: <code>[math]::Min(1, $v)</code> picks the integer overload and rounds <code>$v</code>, so a 0..1 progress value jumps from 0 to 1. Type both arguments: <code>[math]::Min([double]1, $v)</code>.</p>
<h2>Putting the clip on the timeline</h2>
<p>Generated files go to <code>materials/aigenerated/&lt;project&gt;/</code>, never overwriting, with the generator script kept next to the project, so a changed word or font means re-running the script, not redrawing by hand. Then two commands of the project CLI:</p>
<pre><code class="language-powershell">engine\kdp.ps1 bin-add -Project projects\demo\demo.kdenlive -File materials\aigenerated\demo\text-12.mov
engine\kdp.ps1 add -Project projects\demo\demo.kdenlive -Bin 5 -Track V2 -At 14.2   # 5 = the id bin-add printed
</code></pre>
<p>Overlays go on their own track above the picture. If the picture clip has a push-in or whip, the same motion filters are copied onto the overlay so both move together. The open Kdenlive reloads and the user sees the clip appear (how that works safely is part 6).</p>
<h2>Takeaways</h2>
<ul>
<li>Make every scene a pure function of time; parallelism and motion blur come for free.</li>
<li>Headless Edge plus DevTools is a renderer every Windows PC already has.</li>
<li>For long pieces, keep compositing and encoding inside the page (float16 canvas + WebCodecs).</li>
<li>Ship alpha overlays as PNG-in-MOV, and keep the generator so the clip can be regenerated.</li>
</ul>
<p>Windows only, Kdenlive 26.08.3, MIT licensed: <strong><a href="https://github.com/vladtarrow/movie-engine">https://github.com/vladtarrow/movie-engine</a></strong>. To try it, clone the repo and run:</p>
<pre><code class="language-powershell">.\setup.cmd
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Finding menu items in 31 languages by reading the app's own translation files]]></title><description><![CDATA[Also published on DEV. Part 3 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier: Part 1…]]></description><link>https://movie-engine.hashnode.dev/finding-menu-items-in-31-languages-by-reading-the-app-s-own-translation-files</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/finding-menu-items-in-31-languages-by-reading-the-app-s-own-translation-files</guid><category><![CDATA[Windows]]></category><category><![CDATA[i18n]]></category><category><![CDATA[Powershell]]></category><category><![CDATA[automation]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Mon, 23 Nov 2026 04:12:09 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/finding-menu-items-in-31-languages-by-reading-the-apps-own-translation-files-l2c">DEV</a>.</em></p>
<p><em>Part 3 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier: <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">Part 1, the overview</a>, <a href="https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4">Part 2, UI Automation without stealing focus</a>.</em></p>
<p>Movie Engine makes a running Kdenlive reload a project by pressing File &gt; Revert through Windows UI Automation. UI Automation finds controls by their <strong>name</strong>, and the name is whatever the interface shows. In English it is "File" and "Revert". In German it is "Datei" and "Zuletzt gespeicherte Fassung". In Japanese it is "ファイル(F)" and "戻す(V)".</p>
<p>The launchers start Kdenlive in English by default (<code>LANGUAGE=en_US</code>), but a user who prefers their own language sets <code>MOVIE_ENGINE_UI_LANG=de</code> and the automation must still work. This post is about where the names come from and how each language is checked.</p>
<h2>Don't guess translations, read them</h2>
<p>The tempting approach is to type the names in from memory or a translation service. That fails quietly: KDE's German for "Revert" is not "Zurücksetzen", it is "Zuletzt gespeicherte Fassung". The only correct source is the translation catalog the program actually loads.</p>
<p>The portable Kdenlive 26.08.3 for Windows ships them under <code>bin/data/locale/&lt;lang&gt;/LC_MESSAGES/</code>. The strings we need come from four files:</p>
<table>
<thead>
<tr>
<th>String</th>
<th>File</th>
<th>Format</th>
</tr>
</thead>
<tbody><tr>
<td>File (menu)</td>
<td><code>kxmlgui6.mo</code></td>
<td>GNU gettext</td>
</tr>
<tr>
<td>Save, Revert, Open Recent</td>
<td><code>kconfigwidgets6.mo</code></td>
<td>GNU gettext</td>
</tr>
<tr>
<td>Create Folder, "Loading project"</td>
<td><code>kdenlive.mo</code></td>
<td>GNU gettext</td>
</tr>
<tr>
<td>Information (message box title)</td>
<td><code>kwidgetsaddons6_qt.qm</code></td>
<td>Qt Linguist</td>
</tr>
</tbody></table>
<h2>Reading a .mo file</h2>
<p>GNU <code>.mo</code> is a simple binary format: a magic number, a count, and two tables of (length, offset) pairs pointing to the original and the translated strings. Here is a minimal reader in PowerShell (written for this post and checked against the shipped files):</p>
<pre><code class="language-powershell">function Read-Mo([string]$path) {
    $b = [IO.File]::ReadAllBytes($path)
    $u32 = { param($o) [BitConverter]::ToUInt32($b, $o) }
    if ((&amp; $u32 0) -ne 2500072158) { throw 'not a little-endian .mo file' }   # 0x950412de
    $count = &amp; $u32 8; $orig = &amp; $u32 12; $trans = &amp; $u32 16
    $utf8 = [Text.Encoding]::UTF8
    $map = @{}
    for ($i = 0; $i -lt $count; $i++) {
        $ol = &amp; $u32 ($orig + 8 * $i); $oo = &amp; $u32 ($orig + 8 * $i + 4)
        $tl = &amp; $u32 ($trans + 8 * $i); $to = &amp; $u32 ($trans + 8 * $i + 4)
        # msgctxt is joined to msgid with 0x04, plural forms are split by 0x00
        $id = $utf8.GetString($b, $oo, $ol).Split([char]4)[-1].Split([char]0)[0]
        $map[$id] = $utf8.GetString($b, $to, $tl).Split([char]0)[0]
    }
    $map
}
(Read-Mo "$loc\de\LC_MESSAGES\kconfigwidgets6.mo")['Re&amp;vert']   # "Zuletzt gespeicherte Fassung" once the &amp; is removed
</code></pre>
<p>Notice the magic number is written in decimal. In Windows PowerShell 5.1, <code>0x950412de</code> is parsed as a <em>negative</em> <code>Int32</code>, so comparing it with the unsigned value read from the file always fails. I hit that while writing this post.</p>
<p>The keys carry the keyboard accelerator: <code>&amp;File</code>, <code>Re&amp;vert</code>, <code>Open &amp;Recent</code>. UI Automation reports names without the <code>&amp;</code>, so it is stripped. CJK translations keep the accelerator in brackets at the end, <code>ファイル(F)</code>, and that part stays: it is what UIA reports.</p>
<h2>Reading a .qm file: there is no source text</h2>
<p>Qt's <code>.qm</code> format surprised me. It is a sequence of tagged blocks (<code>0x42</code> hash table, <code>0x69</code> messages, ...), and the messages block holds translations as UTF-16BE, but <strong>modern <code>lrelease</code> drops the English source text</strong>. Qt looks a message up by an ELF hash of the source string. So to read "Information" you hash "Information" and follow the hash table:</p>
<pre><code class="language-powershell">[uint32]$h = 0
foreach ($c in [Text.Encoding]::UTF8.GetBytes($source)) {
    $h = (($h -shl 4) -band 0xFFFFFFFFL) + $c
    $g = $h -band 0xF0000000L
    if ($g) { $h = $h -bxor ($g -shr 24); $h = $h -band (-bnot $g -band 0xFFFFFFFFL) }
}
if (-not $h) { $h = 1 }
# then: entries of the 0x42 block are (hash, offset into 0x69); at that offset,
# tag 3 = translation (be32 length + UTF-16BE), tag 7 = context, tag 1 = end of message
</code></pre>
<p>That gives <code>Informationen</code> for German, <code>Ilmoitus</code> for Finnish, <code>Bilgi</code> for Turkish: the same values that are in the engine.</p>
<h2>What the engine stores</h2>
<p>The engine does not parse catalogs at run time. The names were extracted once and live in <code>engine/tools/kd-ui.ps1</code>, English first:</p>
<pre><code class="language-powershell">$script:KdNames = @{
    File    = @('File', 'Файл', 'Datei', 'Fichier', 'Archivo', 'Arquivo', '文件(F)', 'ファイル(F)', 'Plik', ...)
    Revert  = @('Revert', 'Восстановить', 'Відновити', 'Zuletzt gespeicherte Fassung', 'Annuler', ...)
    ...
}
function New-KdNameCondition([string]$key) {
    $conds = @($script:KdNames[$key] | ForEach-Object {
        New-Object System.Windows.Automation.PropertyCondition($script:KdAE::NameProperty, $_) })
    if ($conds.Count -eq 1) { return $conds[0] }
    New-Object System.Windows.Automation.OrCondition(, [System.Windows.Automation.Condition[]]$conds)
}
</code></pre>
<p>One <code>OrCondition</code> covers every language at once, so the code that opens the File menu does not need to know which language is running. Dialog titles ("Information", "Loading project", the "revert to last saved version?" question) are matched by regular expressions built the same way. Several languages share a word ("Fil" is the File menu in Danish and Norwegian Bokmål, "Datoteka" in Bosnian, Croatian and Slovenian), so the File list has fewer entries than there are languages.</p>
<p>The supported set is 31 interface languages: en, ru, uk, de, fr, es, pt_BR, zh_CN, ja, it, pl, ar, bs, ca, cs, da, el, et, fi, ga, hr, hu, lt, lv, nb, nl, ro, sk, sl, sv, tr.</p>
<h2>Checking each language on an invisible desktop</h2>
<p>A name table is only a claim until a real Kdenlive in that language confirms it. <code>engine/tools/kd-langcheck.ps1</code> starts a throw-away Kdenlive with <code>MOVIE_ENGINE_UI_LANG</code> set, on a separate Windows desktop created by <code>kd-hidden.ps1</code> (<code>CreateDesktop</code>, so it can never take my focus). It reads the menu bar, finds the File menu and the Save button, expands File and looks for Revert and Open Recent:</p>
<pre><code class="language-powershell">$menu = $file.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern)
try { $menu.Expand() } catch { }
for ($i = 0; $i -lt 30 -and -not ($revert -and $recent); $i++) {
    Start-Sleep -Milliseconds 200
    if (-not $revert) { $revert = Find-KdNamed $file 'Revert' }
    if (-not $recent) { $recent = Find-KdNamed $file 'Recent' }
}
</code></pre>
<p>It exits 0 only when all four were found. Each run's report is kept in <code>docs/proof/language-&lt;lang&gt;.txt</code>, for example:</p>
<pre><code class="language-plaintext">language check, 2026-11-23 05:12, MOVIE_ENGINE_UI_LANG='ja'
menu bar: ファイル(F) | 編集 | ビュー | メディア | シーケンス | ツール | モニタ | マーカー | 設定(S) |  | ヘルプ(H)
File menu found: True as 'ファイル(F)'
Save button found: True as '保存(S)'
Revert item found: True as '戻す(V)'
</code></pre>
<h2>The quirk: German Kdenlive with Russian menus</h2>
<p>The German check passed, but its menu bar looked like this:</p>
<pre><code class="language-plaintext">menu bar: Datei | Bearbeiten | Ansicht | Мультимедиа | Последовательность | Werkzeug | ...
</code></pre>
<p>"Media" and "Sequence" are Russian. Those strings are missing from the German translation, and instead of falling back to English, the missing ones fell back to the <strong>Windows display language</strong> of the test machine, which is Russian. The four items the engine needs are translated, so the check passes, but it is a reminder that an interface can mix languages, and that a table built on one PC is only proven for what it actually checked.</p>
<p>Two more notes from the docs: a language Kdenlive has no <code>kdenlive.mo</code> for (for example Swahili or Amharic) shows English menus, which already work. Adding a new language means adding its names to <code>kd-ui.ps1</code> and running <code>kd-langcheck.ps1</code> with <code>MOVIE_ENGINE_UI_LANG</code> set to it.</p>
<h2>Takeaways</h2>
<ul>
<li>If you automate a localized UI by name, take the names from the catalogs the program loads.</li>
<li><code>.mo</code> is easy to parse; <code>.qm</code> needs the ELF hash of the source text.</li>
<li>Verify each language against a real instance, and keep the raw report.</li>
</ul>
<p>Windows only, Kdenlive 26.08.3, MIT licensed: <strong><a href="https://github.com/vladtarrow/movie-engine">https://github.com/vladtarrow/movie-engine</a></strong>. To try it, clone the repo and run:</p>
<pre><code class="language-powershell">.\setup.cmd
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Driving a Windows desktop app from an AI agent without stealing focus]]></title><description><![CDATA[Also published on DEV. Part 2 of a series on Movie Engine, an open-source setup where Claude Code or Codex edits real Kdenlive video projects while the…]]></description><link>https://movie-engine.hashnode.dev/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus</guid><category><![CDATA[Windows]]></category><category><![CDATA[Powershell]]></category><category><![CDATA[automation]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Mon, 23 Nov 2026 04:11:18 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4">DEV</a>.</em></p>
<p><em>Part 2 of a series on Movie Engine, an open-source setup where Claude Code or Codex edits real Kdenlive video projects while the editor stays open. Part 1: <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">How I let an AI agent edit video in Kdenlive without touching my mouse</a>.</em></p>
<p>An AI agent that edits my video project has to poke the running editor now and then: "save what the user just did", "re-read the file I just wrote". The obvious tools for that on Windows are <code>SendKeys</code>, <code>SetForegroundWindow</code> and synthetic mouse clicks. All three are off limits in this project, because I am sitting at the same machine, typing into some other window. A keystroke sent to "the active window" lands wherever my cursor happens to be.</p>
<p>So the rule is strict: <strong>no focus changes, no keystrokes, no mouse input.</strong> Kdenlive 26.08.3 on Windows has no external control API (its D-Bus interface is compiled only on Linux), so the agent edits the <code>.kdenlive</code> file and then has to make the open editor notice. This post is about how that last part works, and the two performance traps I hit on the way.</p>
<h2>UI Automation patterns instead of input</h2>
<p>Windows UI Automation (UIA) exposes controls as a tree of elements, and many elements support <em>patterns</em>: <code>InvokePattern</code> (press a button or menu item), <code>ExpandCollapsePattern</code> (open a menu), <code>WindowPattern</code> (close a window). Calling a pattern goes straight to the control. Nothing is focused, nothing is typed. Qt implements UIA for its widgets, so Kdenlive answers.</p>
<p>Reloading the project is File &gt; Revert. In code (from <code>engine/tools/kd-ui.ps1</code>, simplified):</p>
<pre><code class="language-powershell">$root = $script:KdAE::FromHandle($main.Handle)
$file = Find-KdFileMenu $root
$menu = $file.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern)
$menu.Expand()
$item = Find-KdNamed $file 'Revert'     # search inside this menu only
$item.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()
</code></pre>
<p>"Do I have unsaved edits?" needs no menu at all: Kdenlive's toolbar Save button is enabled exactly when the document is modified, so <code>IsEnabled</code> on that element is the answer. Pulling the user's edits is <code>Invoke()</code> on the same button.</p>
<p>To <em>see</em> the editor, the agent never screenshots the desktop. <code>engine/kdwin.ps1</code> captures only Kdenlive's own window with <code>PrintWindow</code>:</p>
<pre><code class="language-powershell">$dc = $g.GetHdc(); [void][KdWin]::PrintWindow($h, $dc, 2); $g.ReleaseHdc($dc)
</code></pre>
<p>Flag <code>2</code> (<code>PW_RENDERFULLCONTENT</code>) makes it work for GPU-drawn content. One limitation: Qt popup menus come back black, so menus are read through UIA, not pixels.</p>
<h2>Trap 1: one search froze the editor for a minute</h2>
<p>The natural way to find an element is <code>FindFirst(TreeScope.Descendants, condition)</code> on the main window. It works fine on an empty project. On a project with about 1000 clips, one such call <strong>froze Kdenlive for 30 to 70 seconds</strong> (measured 2026-11-22). The reason is that Qt builds an accessibility object for every timeline item when the tree is walked, and a descendant search walks all of it.</p>
<p>The fix is to never search the whole window. Every finder in <code>kd-ui.ps1</code> goes down only branches it knows. The File menu lives in the menu bar, so look at children of menu bars only:</p>
<pre><code class="language-powershell">function Find-KdFileMenu($root) {
    $bars = New-Object System.Windows.Automation.PropertyCondition(
        $script:KdAE::ControlTypeProperty, [System.Windows.Automation.ControlType]::MenuBar)
    $named = New-KdNameCondition 'File'
    foreach ($bar in Get-KdChildren $root $bars) {
        $item = $bar.FindFirst($script:KdScope::Children, $named)
        if ($item) { return $item }
    }
}
</code></pre>
<p>The timeline widget itself (needed to confirm a reload, see below) is found by a breadth-first walk that only enters known container classes and stops at the timeline instead of going into it:</p>
<pre><code class="language-powershell">$script:KdContainers = '(MainWindow|DropArea|::Group|::Stack|QStackedWidget|DockWidget|TimelineTabs|QSplitter|MultiSplitter)$|^QWidget$'
</code></pre>
<p><code>Find-KdNamed</code>, which does use <code>Descendants</code>, is only ever called on small roots: an open menu, a dialog, the menu bar.</p>
<h2>How do you know the reload really happened?</h2>
<p><code>Invoke()</code> returning is not proof. On a big project it may time out after about 60 seconds while the load is still running, or the click may get lost. The engine checks something that must change: <strong>the timeline widget is rebuilt by every real reload</strong> (verified 2026-11-22), so its UIA runtime id changes.</p>
<pre><code class="language-powershell">$before = Get-KdTimelineId $main
# ... invoke Revert, then poll ...
$now = Get-KdTimelineId $main
if ($now -ne $before) { return New-KdResult 0 "reload confirmed" }
</code></pre>
<p><code>kd-reload.ps1</code> exits 0 only on that confirmation. It also never answers Kdenlive's "discard unsaved changes?" question with yes: that dialog is closed with <code>WindowPattern.Close()</code>, which maps to Cancel, and the script reports "unsaved edits" (exit 2) so the agent pulls them first. A modal "Loading project" window is treated as progress, not as a blocking dialog.</p>
<h2>Trap 2: <code>kdenlive.exe project.kdenlive</code> took 12 minutes</h2>
<p>Opening a big project the obvious way, with the file on the command line, took about 12 minutes. Stack samples showed why: with a file argument Kdenlive builds the whole timeline first and lays out its panels afterwards. Every panel button that changes raises a UIA event, and for each one Qt walks every timeline item.</p>
<p>Started <em>without</em> a file, Kdenlive lays out its panels over an empty timeline, which is cheap. <code>engine/tools/kd-open.ps1</code> does exactly that: it writes the project into the profile's Recent Files list, starts the empty editor, and then opens File &gt; Open Recent &gt; the project through UIA patterns. The same project loaded in <strong>139 seconds</strong>.</p>
<p>Two more details made the launcher behave:</p>
<ul>
<li><code>Process.Start</code> with <code>UseShellExecute=$false</code> passes the output pipe on (the caller hangs until Kdenlive is closed) and ignores <code>WindowStyle</code>. The launcher calls <code>CreateProcess</code> directly with <code>SW_SHOWMINNOACTIVE</code> (7).</li>
<li>The splash screen uses up that show flag, so the main window still appears restored. The launcher watches for it and minimizes it with <code>ShowWindowAsync(h, 7)</code>, which does not activate anything.</li>
</ul>
<p>Honest limitation: even so, the empty editor takes the keyboard focus for about 3 seconds as it appears (measured 3.2 s on the real desktop). So agents ask before starting the editor while I am working. Once it is open, pulling and reloading use only UIA patterns.</p>
<h2>Tests run on a desktop nobody sees</h2>
<p>Test instances never run on my desktop. <code>engine/tools/kd-hidden.ps1</code> calls <code>CreateDesktop</code> and starts the test script on that invisible desktop inside a job object. Windows there cannot take my focus, and UIA on that desktop cannot even see my Kdenlive. The live-update test (<code>kd-livetest.ps1</code>) passes 13 of 13 checks on a small project; the big-project run is listed as failed-then-fixed-not-rerun in <code>docs/kdenlive-proof.md</code>.</p>
<h2>Takeaways</h2>
<ul>
<li>UIA patterns (<code>Invoke</code>, <code>ExpandCollapse</code>, <code>WindowPattern.Close</code>) let an agent drive a GUI without touching input.</li>
<li>Never <code>FindFirst(Descendants)</code> from the main window of a heavy Qt app. Walk known branches.</li>
<li>Confirm actions by an effect that must change, not by a call returning.</li>
<li>How you start an app can matter more than what you do afterwards.</li>
</ul>
<p>Windows only, Kdenlive 26.08.3, MIT licensed: <strong><a href="https://github.com/vladtarrow/movie-engine">https://github.com/vladtarrow/movie-engine</a></strong>. To try it, clone the repo and run:</p>
<pre><code class="language-powershell">.\setup.cmd
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How I let an AI agent edit video in Kdenlive without touching my mouse]]></title><description><![CDATA[Also published on DEV. AI coding agents are good at structure, timing and repetition — exactly the boring parts of video editing. But video editors are…]]></description><link>https://movie-engine.hashnode.dev/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse</link><guid isPermaLink="true">https://movie-engine.hashnode.dev/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse</guid><category><![CDATA[AI]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Vladyslav Tarasenko]]></dc:creator><pubDate>Mon, 23 Nov 2026 03:18:36 GMT</pubDate><content:encoded><![CDATA[<p><em>Also published on <a href="https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa">DEV</a>.</em></p>
<p>AI coding agents are good at structure, timing and repetition — exactly the boring parts of video editing. But video editors are built for a mouse, and an agent that clicks through a GUI takes over your desktop. I wanted Claude Code to edit my videos while I keep using the same editor.</p>
<h2>The problem</h2>
<p>Kdenlive is a great open-source editor, but on Windows it has no automation API: D-Bus control is compiled only on Linux. The forks that add an API are unmaintained or unsafe.</p>
<h2>The approach: edit the file, then ask the editor to re-read it</h2>
<p>A <code>.kdenlive</code> project is MLT XML. Movie Engine edits it with a command line tool (<code>kdp.ps1</code>, about 120 commands). Every command:</p>
<ol>
<li>asks the running Kdenlive to save the user's unsaved edits, through the toolbar Save button via UI Automation, and confirms it;</li>
<li>edits the XML under a lock, after a hash check, with an undo snapshot;</li>
<li>lets a watcher trigger File &gt; Revert in the open editor, and counts it as done only when the timeline widget has really been rebuilt.</li>
</ol>
<p>UI Automation patterns (Invoke, ExpandCollapse) work without focus or keystrokes, so the agent never steals the keyboard. Test editors run on an invisible Windows desktop with their own profile.</p>
<h2>Two surprises</h2>
<ul>
<li>Opening a project with <code>kdenlive.exe project.kdenlive</code> made each UI Automation call walk every timeline item: about 12 minutes on a 1000-clip project. Starting empty and opening via File &gt; Open Recent took 139 seconds.</li>
<li>Kdenlive's menu names depend on the interface language, so the tool reads them from Kdenlive's own translation files (.mo/.qm) — 31 languages, each checked on a hidden desktop.</li>
</ul>
<h2>What Kdenlive can't do, render outside</h2>
<p>Per-letter kinetic text, hand-drawn annotations, 3D UI scenes and long explainer films are rendered with headless Edge and canvas (with real motion blur) and placed on the timeline as ordinary clips. Word timings from Edge TTS make captions and actions fire on the exact spoken word.</p>
<h2>Try it</h2>
<pre><code>git clone https://github.com/vladtarrow/movie-engine.git
cd movie-engine
.\setup.cmd
</code></pre>
<p>Or in Claude Code: <code>/plugin marketplace add vladtarrow/movie-engine</code>. Windows only, MIT licensed.</p>
<p>Repo: <a href="https://github.com/vladtarrow/movie-engine">github.com/vladtarrow/movie-engine</a>. Feedback welcome, especially from people who edit video.</p>
]]></content:encoded></item></channel></rss>