{"slug": "driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus", "title": "Driving a Windows desktop app from an AI agent without stealing focus", "summary": "A developer building Movie Engine, an open-source setup that lets Claude Code or Codex edit live Kdenlive video projects, described driving the Windows editor through UI Automation patterns (InvokePattern, ExpandCollapsePattern) instead of SendKeys, SetForegroundWindow or synthetic mouse clicks, so the agent never steals focus from the user. The developer found that a full-window FindFirst descendant search froze Kdenlive for 30 to 70 seconds on a project with about 1,000 clips, and fixed it by scoping every finder to known branches such as the menu bar and a breadth-first walk that stops at the timeline.", "body_md": "*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: [How I let an AI agent edit video in Kdenlive without touching my mouse](https://dev.to/vladtarrow/how-i-let-an-ai-agent-edit-video-in-kdenlive-without-touching-my-mouse-1faa).*\n\nAn 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 `SendKeys`, `SetForegroundWindow` 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.\n\nSo the rule is strict: **no focus changes, no keystrokes, no mouse input.** 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 `.kdenlive` 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.\n\nWindows UI Automation (UIA) exposes controls as a tree of elements, and many elements support *patterns*: `InvokePattern` (press a button or menu item), `ExpandCollapsePattern` (open a menu), `WindowPattern` (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.\n\nReloading the project is File > Revert. In code (from `engine/tools/kd-ui.ps1`, simplified):\n\n``` php\n$root = $script:KdAE::FromHandle($main.Handle)\n$file = Find-KdFileMenu $root\n$menu = $file.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern)\n$menu.Expand()\n$item = Find-KdNamed $file 'Revert'     # search inside this menu only\n$item.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()\n```\n\n\"Do I have unsaved edits?\" needs no menu at all: Kdenlive's toolbar Save button is enabled exactly when the document is modified, so `IsEnabled` on that element is the answer. Pulling the user's edits is `Invoke()` on the same button.\n\nTo *see* the editor, the agent never screenshots the desktop. `engine/kdwin.ps1` captures only Kdenlive's own window with `PrintWindow`:\n\n``` php\n$dc = $g.GetHdc(); [void][KdWin]::PrintWindow($h, $dc, 2); $g.ReleaseHdc($dc)\n```\n\nFlag `2` (`PW_RENDERFULLCONTENT`) makes it work for GPU-drawn content. One limitation: Qt popup menus come back black, so menus are read through UIA, not pixels.\n\nThe natural way to find an element is `FindFirst(TreeScope.Descendants, condition)` on the main window. It works fine on an empty project. On a project with about 1000 clips, one such call **froze Kdenlive for 30 to 70 seconds** (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.\n\nThe fix is to never search the whole window. Every finder in `kd-ui.ps1` goes down only branches it knows. The File menu lives in the menu bar, so look at children of menu bars only:\n\n``` php\nfunction Find-KdFileMenu($root) {\n    $bars = New-Object System.Windows.Automation.PropertyCondition(\n        $script:KdAE::ControlTypeProperty, [System.Windows.Automation.ControlType]::MenuBar)\n    $named = New-KdNameCondition 'File'\n    foreach ($bar in Get-KdChildren $root $bars) {\n        $item = $bar.FindFirst($script:KdScope::Children, $named)\n        if ($item) { return $item }\n    }\n}\n```\n\nThe 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:\n\n```\n$script:KdContainers = '(MainWindow|DropArea|::Group|::Stack|QStackedWidget|DockWidget|TimelineTabs|QSplitter|MultiSplitter)$|^QWidget$'\n```\n\n`Find-KdNamed`, which does use `Descendants`, is only ever called on small roots: an open menu, a dialog, the menu bar.\n\n`Invoke()` 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: **the timeline widget is rebuilt by every real reload** (verified 2026-11-22), so its UIA runtime id changes.\n\n``` php\n$before = Get-KdTimelineId $main\n# ... invoke Revert, then poll ...\n$now = Get-KdTimelineId $main\nif ($now -ne $before) { return New-KdResult 0 \"reload confirmed\" }\n```\n\n`kd-reload.ps1` exits 0 only on that confirmation. It also never answers Kdenlive's \"discard unsaved changes?\" question with yes: that dialog is closed with `WindowPattern.Close()`, 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.\n\n`kdenlive.exe project.kdenlive` took 12 minutes\nOpening 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.\n\nStarted *without* a file, Kdenlive lays out its panels over an empty timeline, which is cheap. `engine/tools/kd-open.ps1` does exactly that: it writes the project into the profile's Recent Files list, starts the empty editor, and then opens File > Open Recent > the project through UIA patterns. The same project loaded in **139 seconds**.\n\nTwo more details made the launcher behave:\n\n`Process.Start` with `UseShellExecute=$false` passes the output pipe on (the caller hangs until Kdenlive is closed) and ignores `WindowStyle`. The launcher calls `CreateProcess` directly with `SW_SHOWMINNOACTIVE` (7).`ShowWindowAsync(h, 7)`, which does not activate anything.\nHonest 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.\n\nTest instances never run on my desktop. `engine/tools/kd-hidden.ps1` calls `CreateDesktop` 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 (`kd-livetest.ps1`) passes 13 of 13 checks on a small project; the big-project run is listed as failed-then-fixed-not-rerun in `docs/kdenlive-proof.md`.\n\n`Invoke`, `ExpandCollapse`, `WindowPattern.Close`) let an agent drive a GUI without touching input.` FindFirst(Descendants)` from the main window of a heavy Qt app. Walk known branches.\nWindows only, Kdenlive 26.08.3, MIT licensed: **[https://github.com/vladtarrow/movie-engine](https://github.com/vladtarrow/movie-engine)**. To try it, clone the repo and run:\n\n```\n.\\setup.cmd\n```\n\n", "url": "https://wpnews.pro/news/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus", "canonical_source": "https://dev.to/vladtarrow/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus-2gg4", "published_at": "2026-11-23 04:03:27+00:00", "updated_at": "2026-11-23 04:11:53.745074+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "artificial-intelligence"], "entities": ["Movie Engine", "Kdenlive", "Claude Code", "Codex", "Windows UI Automation", "Qt"], "also_reported_by": [], "takeaway": "On Windows, drive Qt apps like Kdenlive via UI Automation patterns (InvokePattern, ExpandCollapsePattern) rather than keystrokes, and never run a full-window descendant search: it froze Kdenlive for 30-70 seconds on a ~1,000-clip project, so scope finders to known branches.", "recommendation": {"advice": "Scope UI Automation searches to known branches (menu bars, container classes) instead of TreeScope.Descendants on the main window; a full descendant walk froze Kdenlive for 30-70 seconds on a 1,000-clip project.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus", "markdown": "https://wpnews.pro/news/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus.md", "text": "https://wpnews.pro/news/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus.txt", "jsonld": "https://wpnews.pro/news/driving-a-windows-desktop-app-from-an-ai-agent-without-stealing-focus.jsonld"}}