How Keyhac2 is tested, the reusable harness patterns, and what has been verified live on each OS.
.venv/bin/python -m pytest — the keymap engine
runs against scripted fakes (keyhac/platform/fake.py), no OS access, no
permissions. Key expressions, modifier planes, one-shot, multi-stroke, user
modifiers, replace_key, focus conditions, InputContext reconciliation, mouse
translation, replay normalization.MemoryBackend (snapshot, style_at, feed_event).tests/test_win_*.py / tests/test_mac_*.py drive the real
OS APIs — they need a desktop session, and on macOS the Accessibility permission.
Tests marked slow launch real third-party apps; skip with -m 'not slow'.desktop. They
get in the way of whatever you are doing, and what you are doing gets in the
way of them, so pytest skips them unless it is given --desktop - in a
VM, which is what the VM test run (#293) is for. A new test of that kind
gets the mark: a whole module with pytestmark = pytest.mark.desktop,
otherwise the class or the function. A test that only reads the OS (the
keyboard layout, a timing) stays unmarked. The mark is quality-loop’s pytest
plugin (addopts in pyproject.toml), shared with XeFM, and so is
host_only: a test of the host-side tooling - what stages a VM run -
which a guest skips; pytest --host-only runs those alone.tests/conftest.py points HOME
and USERPROFILE at a fresh temporary directory for the whole run, so no
test reads the runner’s own ~/.keyhac (its config.py, settings.json,
extensions) and passes or fails with what that machine holds. A test that
needs a home of its own still sets one itself. A test that starts another
application passes it the real_home_environ fixture: Windows’ Notepad,
started with USERPROFILE pointing at the empty home, crashes within
seconds.make test-vm GUEST=qa-win / GUEST=qa-mac runs the whole suite with
--desktop in a VM from the shared images (~/.config/quality-loop/guests.toml):
the working tree, PuiKit and quality-loop staged, the third-party packages
installed into a fresh venv, pytest in the desktop session through
quality-loop’s runner (Windows: a scheduled task with python.exe; macOS:
SSH). ARGS= is for pytest; the log and the JUnit XML land in
temp/vm-test-<guest>-<time>/ (tools/vm.py). PACKAGES=pypi installs
PuiKit and quality-loop from PyPI as pyproject.toml names them instead of
staging this checkout’s - what a user’s pip gets. The macOS image
(qa-mac-2026-11-15, python.org 3.15 and 3.15t; 3.14 removed) grants
sshd-keygen-wrapper, under which the Python started over SSH runs,
“Device Control and Data Access” (macOS 27’s
Accessibility and Input Monitoring) and has Japanese Romaji input, so the
window, mouse and IME tests run there. The Windows image (QA-2026-11-15, 3.14 uninstalled)
is a snapshot of the VM shut down, so each run boots it, as each Tart
clone does: python.org’s 3.15t x64 (emulated, the VM being Arm;
ARCH=arm64 runs the suite under the image’s native ARM64 3.15t
instead, and make release-test does both), the Japanese Microsoft IME, automatic
sign-in for qa, and “Suggest ways to finish setting up my device” off,
whose full-screen page would otherwise cover the desktop at sign-in. A
run takes about three minutes on macOS and six on Windows, boot included.
The stage is copied from the working
tree once the VM is up, not when the command starts: do not switch branches
or edit files until it is (about the first minute) - a checkout half way
through the copy stages a mix of both branches, and the run then fails in
ways neither has. The same holds for a quality-loop run in a guest.
The suite never shows a VM window, whatever visible says in
guests.toml: a window on your screen can take a click or a key meant for
something else, and the desktop tests drive the guest’s own focus and input
sources. It is the suspected cause of tests/test_mac_ime.py failing in two
make tag runs while the Tart window was on screen (#353). A VMware VM has no
window here in any case.make release-test is what a release is tested on, and what make
tag gates on: pytest --host-only here, then the whole suite with
--desktop in qa-mac and qa-win on PyPI packages, one after the other.
The VMs are shared with XeFM: a run-vm left open in either product holds
them.make run-vm GUEST=qa-mac is a hand check in a VM: this working tree’s
Keyhac started in the guest’s desktop session (from the image’s Python and a
fresh venv, as the suite runs) with an empty home on the stage, until Enter. Hand
checks go there rather than on your machine. This is what visible = true
is for: a Tart VM shows its window, and a VMware VM is suspended for you to
resume in the Fusion app.tools/hook_echo.py echoes key events through the real
hook; --stress-ordering manufactures the injected-vs-physical race (see below).qa/)A packaged skill is a snapshot with no repository behind it, and this
repository is full of the answers. So “is the skill self-contained?” cannot be
asked from a session that has read doc/, examples/actions/ or the source.
That session cannot unsee them. make qa asks it properly, through
quality-loop (a dev dependency; the
design is #205):
qa/scenarios/ is Markdown: the prompt a user would type,
the screen it needs, and its Must / Must not lists.
qa/scenarios/_always.md holds what every room is held to. A prompt names
Keyhac and asks for something kept: the AI integration is for actions the
user runs again (from a key or the chooser’s Run page), and a one-off
operation is computer use’s job, not Keyhac’s. So an action prompt says why
it comes round again, and asks for one run now to show it works.--restricted, with Keyhac’s MCP and no shell. Its file tools reach the
run’s ~/.keyhac and Desktop, the setup the skill asks the user for - unless
the scenario’s front matter says access = "mcp": that room, labelled
.mcp, reaches neither, as in Claude Desktop with no folder added, and
config.py and extensions/ are Keyhac’s tools’ alone. The MCP endpoint is
allowed and the checkout is not: reading the screen through Keyhac’s own
tools is what the skill tells an author to do.HOME: its
~/.keyhac and ~/Desktop are the run’s, and one of qa/configs.py’s
fixtures (template, short, grown) is its config.py - the one the
scenario’s front matter names (config = "short"), the template otherwise. There is nothing to
put back after a run that died. Your own Keyhac has to be quit for the
length of a run - two cannot both hold the keyboard - and the run holds its
single-instance lock so it cannot start halfway.qa/run.py SCREENS) and afterwards writes REPORT.md: problems with
a severity and a kind, cited from evidence. qa/evidence.py gives it that
evidence. replay loads the room’s config in Keyhac’s own engine and
presses keys through the fake hook. The other tools read the fixture page’s
record, Keyhac’s tool calls and the CSVs against the screens’ ground truth.FINDINGS.md beside the rooms (cleanroom/, gitignored)
gathers every report, most severe first. What to act on is yours to decide.
A problem’s id is what the next run is compared against
(quality-loop findings), and how a finding is filed once.Runs are authorized by a person. They cost model time, they swap your config.py, and screen scenarios open windows.
make qa CASE=11 # attached; quit your own Keyhac first
.venv/bin/quality-loop run 11 # the same, in the background
.venv/bin/quality-loop watch # follow it: run.log and status.json
.venv/bin/quality-loop findings # new / still there / gone / back
In a VM (#271), the run’s Keyhac is off this machine’s keyboard and
screen, and your own Keyhac can keep running. Set KEYHAC_QA_GUEST to an
SSH host alias for the VM:
KEYHAC_QA_GUEST=qa-mac make qa CASE=13
The VM layer is quality-loop’s (quality_loop.guest, its
docs/guests.md), shared with XeFM (xefm#750); qa/guest.py keeps only
what is Keyhac’s: what is staged and how Keyhac starts. What that alias
means on this machine goes in ~/.config/quality-loop/guests.toml
(KEYHAC_QA_GUESTS names another file), outside the repository: the shared
folder as <host path>=<guest path>, the image’s interpreter as python
(required for a Windows guest), and the VM itself, so that the run starts it
from a clean state and puts it away afterwards.
Keyhac’s runs use the image’s free-threaded Python, which is what the
apps embed (#369): free_threaded_python in the table, and on the Windows
guest free_threaded_python_arm64 for --arch arm64. python stays as it
was, since the table is shared and XeFM still runs on it. make test-vm
(and so make release-test) checks the interpreter has the GIL off before
it stages anything, and stops if not; the suite’s
test_nothing_the_apps_import_turns_the_gil_back_on then checks that every
dependency, as that guest installs it, keeps it off. On qa-mac the
free-threaded framework (PythonT.framework, bundle org.python.pythont)
needs no grant of its own: started over SSH, it runs under the
Accessibility and Input Monitoring grant to sshd-keygen-wrapper.
tart = "<base VM>". The run clones the base, starts the clone
with the share as --dir, reaches it at the clone’s own address, and
deletes it afterwards.vmx, snapshot, vm_password (the VM’s encryption
password, which vmrun needs for a VM with a vTPM) and smb,
smb_password. The run reverts to the snapshot, resumes the VM with
vmrun start nogui, mounts the share again (a revert drops it), and waits
for the guest’s clock. Afterwards it unmounts the share and shuts the VM
down. Quit the Fusion app first, or vmrun cannot start the VM.keychain:<service> is read from the
login Keychain when the run needs it.Without a VM in the table, the guest is used as it is, already running.
KEYHAC_QA_SHARE overrides the table’s share.
Claude stays on the host: the room, the operator, the evidence and
cleanroom/. The run’s home and a copy of this working tree go on the
share. Keyhac is started in the guest’s desktop session, and its endpoint is
forwarded over SSH, so the host’s own bridge reaches it. qa/guest.py has
the details.
Both have run scenarios end to end (13 on both, 12 on macOS). On both, the run’s Keyhac starts the way the test suite does: no Keyhac is used from the image, its free-threaded Python (3.15t, fixed per image) gets a fresh venv for the run with the third-party packages - pyproject.toml’s and PuiKit’s - from a pip cache on the share, and PuiKit is ours, so it is staged from this checkout’s environment, not installed. Everything under test is this checkout’s. (Until 2026-11 a macOS guest ran the staged keyhac/ inside the image’s Keyhac.app, whose bundled PuiKit went stale the first time the pin was raised past it, and every run stopped at start-up.)
tart run --dir=qa:<host path>, mounted
in the guest under /Volumes/My Shared Files/. qa/daemon.py is
started over SSH, which reaches the desktop session, under the image’s
Accessibility and Input Monitoring grant to python.org’s Python and
sshd-keygen-wrapper. Once the console is up, Keyhac brings Finder back
to the front.pythonw.exe runs qa/daemon.py from a scheduled task, through
quality-loop’s launcher; pythonw because cmd.exe would put a terminal
window on the desktop. The task is XML because the ScheduledTasks cmdlets
need CIM, which refuses a standard user over SSH. Once the console is up,
Keyhac gives the foreground back to the desktop. A first run takes about
70s from revert to Keyhac’s endpoint.The guest is the test environment. Start each run from a clean state: a Tart clone of a base image, deleted afterwards, or a VMware snapshot taken while the VM was running, reverted to before the run, as above. What the clean state needs, found the hard way:
get_focus
answers whatever window is in front: a leftover PowerShell window, or a
system prompt.sshd-keygen-wrapper granted
Accessibility and Input Monitoring, and no permission prompt left to
appear on the way: an unanswered one keeps the focus for the whole run.
Python’s socket.getfqdn("127.0.0.1") raises the Local Network prompt,
which is why the MCP server never calls it.Screens go up in the guest. The adapter’s screen_backend() hands the
operator quality_loop.guest.screens in place of this machine’s backend.
Each screen_open / screen_close runs quality-loop’s own Safari / Terminal
or Edge / Windows Terminal code in the guest, from the run’s stage. On macOS that goes over SSH; on Windows it
goes through a scheduled task in the desktop session. The pages stay served on
the host’s 127.0.0.1, and a reverse tunnel (ssh -R, same port) makes that
address the guest’s too, so the page’s events come back unchanged. A
terminal screen’s script runs with the image’s interpreter in the guest.
What the clean state needs for screens:
HideFirstRunExperience policy (HKLM\SOFTWARE\Policies\Microsoft\Edge,
DWORD 1) in the snapshot does that.qa/quality-loop.toml names qa/run.py as the adapter for the
quality-loop command. The conductor skill
(.claude/skills/quality-loop/, installed and upgraded only by
quality-loop init, never edited by hand) runs the loop with you: plans
from qa/PLAN.md, runs, reads the findings, files them as Issues, fixes what
you choose and retests, under a policy you set. Ask Claude Code in this
checkout to “run the QA loop”.
tests/test_qa.py checks, without a room, that every scenario parses and names
declared screens, that every fixture config loads on both platforms, that the
evidence tools answer correctly on rooms whose outcome is known, and that the
quality-loop command finds this adapter and its scenarios check.
qa/action_rules.py holds the skill’s mechanical rules for an action
(waits, not sleeps; no coordinates; bounded loops; …). The operator runs it
on a room’s action as rules <room>, and tests/test_action_authoring_evals.py
calibrates it both ways: the hand-written examples pass, and
qa/fixtures/violates_every_rule.py trips every rule.
tests/test_mac_hook.py unit-tests the macOS
deferral state machine against faked Quartz calls — the ordering machinery is
testable without a tap.tools/hook_echo.py --stress-ordering posts events from a
third private CGEventSource (macOS) / with an unsigned dwExtraInfo SendInput
(Windows) that the hook must classify as real, racing them against Keyhac’s own
output. 100/100 rounds green on macOS, 50/50 on Windows — and a crippled-hook
negative control confirms the harness actually catches violations. This validated
the SendInput queue-order assumption behind the send() contract empirically.WinInputHook, real config loading, real focus provider/console, the same wiring
main.py does — and play the user with untagged SendInput (no Keyhac
dwExtraInfo sentinel), which the hook classifies as real. A probe window records
every WM_KEYDOWN/WM_CHAR that reaches an app. No subprocess, so no
single-instance-guard collision: a concurrently running production Keyhac is
untouched (its hook sits later in the LL chain; the harness binds only F13–F24,
which no human config uses). Lives in tests/test_win_typing_load.py.WH_KEYBOARD_LL is synchronous, so typing lag
is the callback duration, and a callback overrunning LowLevelHooksTimeout
(300 ms) gets Keyhac silently unhooked. The harness times the callback and
reports percentiles, which turns “does typing feel OK” into a number.SystemLoad spawns subprocesses; GILLoad is the separate, deliberate
in-process case.type_keys now watches focus on every pump and skips if it
ever left the probe. This is what turned an intermittent red into an honest
skip: the live input tests were failing roughly one run in four, and the
cause was the desktop being busy with other work of ours — Notepad, a
terminal and VS Code being opened and closed by the UIA probes running
alongside. On a quiet desktop the same tests passed 4/4 full runs before the
change and 353/353 after, with no skips, so the guards are inert until
something really is interfering.notepad.exe is a stub that hands the work to one process shared by every
Notepad window, so Popen.terminate() closed nothing and the UIA probes left
a window behind per run. That is precisely the “other work of ours” above.
TestUIAPatternsAgainstNotepad takes the window that was not on screen
before the launch and posts WM_CLOSE to that one, which also stops the
fixture from typing into a Notepad the developer has a real file open in —
find_window(app="notepad") was free to answer with theirs.SendInput returns 1 with no error, the WH_MOUSE_LL
handle is still valid, and no callback ever arrives — while a second wheel
sent immediately after is seen normally, so the hook is alive and the event
went missing. Rare, timing-sensitive, and more likely when other injection
preceded it. Two consequences for tests that inject: retry the stimulus
rather than asserting on one particular event surviving, and where the count
is the assertion, measure what actually reached the engine first. The typing
harness records every vk the hook was handed for exactly that reason — 100
taps is 200 events, and fewer means the burst never arrived to be translated,
which is a skip rather than a translation failure.tests/test_win_ime.py opens the IME; without settling after it
closes one again, the Japanese case of tests/test_win_send_text.py received
日本語入力 for 日本語入力のテスト about one run in five, while that module
alone passed 8/8 and the pair passed 6/6 with the IME test deselected — which
is how it was attributed. A test that changes IME state owns putting it back
and pumping afterwards.tests/test_cancel.py checks the engine’s Esc rule by handing
on_key_event a KeyEvent, and its docstring states the rest as fact:
Keyhac’s own translated output “never reaches on_key_event at all (the
platform layer drops it on its own tag)”. That is a claim about
platform/win/hook.py, and nothing was checking it — so an action pressing
Escape to dismiss a dialog was only believed not to kill itself.
tests/test_win_cancel.py settles it by varying nothing but dwExtraInfo
across real SendInput at a real WH_KEYBOARD_LL hook: untagged cancels
and is swallowed, EXTRA_INFO_OWN never reaches the engine, and
EXTRA_INFO_REPLAY arrives but does not cancel — each also checked for what
the focused window did or did not receive.tests/test_win_layout.py).
kbdus.dll / kbd106.dll export KbdLayerDescriptor() → KBDTABLES, whose
pusVSCtoVK is the scancode→vk truth for that keyboard regardless of what is
plugged in. VkKeyScanEx cannot do this job: kbdjpn.dll picks its variant
from GetKeyboardType(), so on ANSI hardware the “Japanese” layout returns the
US-101 mapping and would cheerfully confirm a wrong JIS table.lpfnWndProc
pointing at the first instance’s freed thunk — the next message faults the
interpreter.900x620
against 450x310 and fails for a reason unrelated to what is under test.
SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2) goes before the first
rect read (tools/bundle_pass.py).console_visible
in settings.json means a console last closed to the tray starts hidden, and
a harness waiting for its window waits forever. Force it and put it back, the
way the frame in the registry already is — this is what kept the bundle pass
from ever running.A Windows guest in VMware Fusion can be built, run and checked from the Mac
without touching its desktop: build.ps1, a Keyhac.exe launch, and a result
file to collect. Everything here addresses the guest as qa-win, an
SSH host alias. Its address, user and key are per machine and live only in
~/.ssh/config, never in this repository.
Why not vmrun. A Windows 11 guest has a vTPM, which makes Fusion
encrypt the VM partially, and vmrun then refuses every operation without
the encryption password, checkToolsState included. SSH needs no password
on the command line and works the same for any VM product.
Guest setup, once. In an elevated PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd; Set-Service sshd -StartupType Automatic
# The rule the capability creates covers the Private profile only, and a
# VM's network is usually Public. Widen it to every profile, but only for
# the host's subnet.
Set-NetFirewallRule -Name OpenSSH-Server-In-TCP -Profile Any -RemoteAddress <host subnet>/24
# An administrator logs in with this file, not ~/.ssh/authorized_keys.
$f = "$env:ProgramData\ssh\administrators_authorized_keys"
Add-Content -Path $f -Value '<public key>' -Encoding ascii
icacls $f /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F"
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell `
-Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
Restart-Service sshd
Add-WindowsCapability downloads from Windows Update and can sit at a full
progress bar for many minutes. Get-WindowsCapability -Online -Name
OpenSSH.Server* in another window says whether it has finished. If it
reports Installed while the first window still sits there, interrupt it
and carry on from Start-Service.
Host setup, once. A key of its own (ssh-keygen -t ed25519 -f
~/.ssh/<key>), whose .pub is the <public key> above, and:
Host qa-win
HostName <guest IP>
User <guest user>
IdentityFile ~/.ssh/<key>
IdentitiesOnly yes
Finding the guest’s IP. A bridged guest gets it from DHCP, so it can
move. Read the MAC from the .vmx (ethernet0.generatedAddress), ping the
subnet once so the ARP table fills, and look the MAC up in arp -an. A
guest with the Public profile does not answer ping, but the ARP entry is
there anyway.
Running things.
ssh qa-win '<PowerShell>' runs in Windows PowerShell 5.1. Python
code with quotes in it does not survive the ssh-to-PowerShell trip; scp
a script file and run that.schtasks /create /tn <name> /tr "<path>\Keyhac.exe" /sc once /st 00:00
/it /f, then schtasks /run /tn <name>. Delete the task afterwards. The
warning that the start time has passed does not matter, since /run
starts it now.Get-Content it. Keep a copy of the
guest’s config.py and put it back afterwards.The #279 entry in the live verification record below used this setup.
tests/test_mac_window.py etc.)finishLaunching(), or its AX server never registers and every query fails with
kAXErrorCannotComplete.frontmostApplication etc.) is refreshed only by run-loop
callbacks — a sleep-polling wait reads the process-start snapshot forever.
Every wait, including fixture discovery polls, must pump the run loop.is_maximized()
turns true races the tail of it; wait for the frame to stop moving
(_wait_settled). Full screen is the opposite trap: the frame jumps at
once, so no frame-based wait sees its ~0.5 s transition, during which a
request the other way is dropped — only a fixed wait
(_wait_full_screen_transition) works. And Fill outlives even its
animation: a frame written in the half second after the window stops
moving is put back, so _wait_fill_transition adds a fixed wait on top
of _wait_settled. Each failure looked like a broken feature in whichever
test ran next.Everything automatable has been run live on both OSes (Windows 11 Home 10.0.26200; macOS 15 on this machine). Highlights and the bugs the passes caught:
UnhookWindowsHookEx behind the hook’s back
(indistinguishable from the OS doing it): four modifier flips with no callbacks
trigger re-install, and consumption works again after. Note: this Windows build
survives a 0.6 s callback stall without unhooking, so the silent-unhook path
cannot be provoked via LowLevelHooksTimeout here.A Win key as a user modifier, on Windows 11 — the pass that produced the
refusal in define_modifier (design-notes.md).
With define_modifier("LWin", "LUser0"): an unbound LWin-G opened the Game Bar
even though Keyhac emits no Win key, and a U0-G action typing “git status” typed
“it status” — the injected g eaten as Win+G, every other letter arriving. Also
measured: replace_key("LWin", 235) + define_modifier(235, "LUser0") changes
nothing; the same user modifier on RAlt is clean; and injecting U-LWin at the
head of the batch fixes the typing and does not open the Start menu. Also
confirmed: Win+L locks the screen with the Win key retired, which is Windows
reserving that combination ahead of the hook chain and is not fixable. Reproducing
any of this needs a real Game Bar, so none of it is in the automated suite.
A scratch probe that consumes a physical key in its own low-level hook while
watching GetAsyncKeyState and a raw input sink shows nothing surviving the
consume, for a Win key or an ordinary one - with the key passed through, both
channels register, which is what makes the negative readable. So the Game Bar is
not reading either of those. Which route it does use is still open.
Checked against keyhac-win 1.83 on the same machine - the released build run
portable (a config.py beside keyhac.exe keeps it off ~/.keyhac), stock
configuration, Keyhac2 shut down: Win+L locks, Win+G opens the Game Bar, and a
U0-G bound to InputKeyCommand("G","I","T",...) types “it status”. The same
command under a real Alt keeps its g and does not move focus to Notepad’s menu
bar - which is cancel_oneshot_win_alt working upstream, and the behavior the
Keyhac2 port reproduces. The behavior is inherited, not a regression.
kt["Alt-G"] bound to an
action, triggered with Alt physically held. The action runs and the menu bar does
not take focus - the VK_LCONTROL tap marks the modifier used before the Alt is
released and again after it is re-pressed. Notepad is the check that matters here:
it has a menu bar to lose focus into.platform/win/uielement.py
is pinned by a test cross-checking it against the Win32 answer for the same
window — two wrong slots were caught that way (BoundingRectangle read a UiaRect
of doubles over a RECT of LONGs; TextRange GetText sat at 12, and slot 11
access-violated).create_unicode_buffer sizes by code points, truncating
surrogate pairs; set_text now encodes UTF-16-LE explicitly).tests/test_mac_ime.py, Kotoeri installed): reading
the state off kTISPropertyInputModeID was verified against both ends
(com.apple.keylayout.US → off, ...RomajiTyping.Japanese → on), and on/off
round-trips. The measurement that shaped the implementation: TISSelectInputSource
on the Roman mode fails with OSStatus −50 (paramErr) because that mode is
disabled on a default Japanese setup — hence the ASCII-capable-layout fallback,
which is also what the Eisu key reaches on such a setup. The probe also showed
the palette input sources (CharacterPaletteIM, 50onPaletteIM, PressAndHold)
report no input mode, so the “first enabled non-Roman mode” selection cannot land
on one. The tests restore the input source they found.tests/test_win_ime.py, Windows 11 26200 with
Microsoft IME for Japanese): 11 live tests, and the pass that caught two real
bugs — the module as first written did not work at all, and its own tests had
passed against the broken behavior because they only ever compared the API with
itself. What broke that circle was checking against ground truth: driving the IME
with the OS’s own VK_IME_ON/VK_IME_OFF and typing aiueo into a real control
to see whether あいうえお or aiueo came out.
open=1 while the frame’s stayed at 0, so
get_status() reported off while Japanese was composing, and set_status(True)
returned True, read back True, and changed nothing visible. Fixed by resolving
through GetGUIThreadInfo(...).hwndFocus; test_the_focused_control_is_asked_not_the_frame
is the guard.set_status(True) reported success, composed nothing, and the flag was gone
after the next layout switch (measured — it is not even latent). Both calls are
now gated on ImmGetProperty(hkl, IGP_CONVERSION). Note ImmIsIME() is not
usable for that gate: it answered true for the US layout too.
The tests switch the probe thread’s layout with ActivateKeyboardLayout, so both
halves — IME layout and plain layout — run on one machine without touching its
settings. Timing held throughout: 0.17 ms per query, far inside SEND_TIMEOUT_MS.
Three application families were swept by hand, since the frame-vs-focus shape
differs between them: Notepad (focus is a RichEditD2DPT child of the frame —
the case that exposed the bug), Edge/Chromium (focus is the frame; correct
either way, and what every Electron app looks like), and a PuiKit window — where
set_status(True) returns False and should: PuiKit associates no input context
with a window until a text field wants one (ImmGetContext → 0), so there is no
IME to open, and the API refuses rather than reporting a success it did not have.
Still not covered on this machine: a TSF-only IME that answers nothing, which
is the only path to None (none installed to test against).doc/dev/ai-integration.md §2): children(),
describe(), get_ui_tree, find_element by DOM id / label / role / text,
table extraction row by row, get_text() on a container whose own value is
empty, get_line_at_caret() at three caret positions, get_selection(),
element_at_point(), and set_manual_accessibility() both on and off. Two
bugs came out of it: _from_ax raised on every range attribute (CFRange
arrives as a tuple, not a struct), and the first cut of format_tree hid an
unchecked checkbox’s 0 behind a truthiness test.
Not covered: Terminal.app and iTerm2 whole-value reads — neither had a
window open — so the terminal half of §6 is still unmeasured on macOS. The
Windows half is measured; see the Text-pattern survey below.macOS waiting and AX notifications (2026-08-06): the three-beat modal
cycle end to end in the real thread architecture — CFRunLoop on the main
thread, the action on a worker, every UI read dispatched back — press,
wait_for_element (modal seen in 10–25 ms), read, press, wait_until_gone
(22 ms), wait_for_stable, a timeout that raised at 1.03 s, and the guard
that refuses to wait on the loop thread. UIObserver (since removed —
see below) delivered
AXWindowCreated / AXCreated / AXValueChanged / AXUIElementDestroyed
for a Finder window opening, and nothing at all for a Safari <dialog>
opening — registered on the application element and on the AXWebArea
alike. Writing AXValue to a plain text input also did nothing, silently.
Those two negatives are why wait_for polls rather than waiting on
notifications, and they are recorded in ai-integration.md §5 and §7.3.
Not covered: notifications from an Electron application. The Safari
result is about WebKit web content, and the separate Chromium/Electron
measurement the same day was about tree exposure — 59 nodes until
set_manual_accessibility(), 119 after — which is a different question.
Expecting the Safari answer to carry over to Electron is reasonable and is
inference, not measurement. tools/ax_notification_pass.py settled it on
macOS: the Finder control passed in the same run (AXFocusedUIElementChanged,
AXCreated, AXValueChanged, AXUIElementDestroyed), Chrome’s tree was
exposed at 522 nodes, and Chrome posted nothing at all across three runs
while a driven in-page change verifiably happened inside the listening window
— a <dialog> opened and closed and the page’s status went “3 items pending”
→ “0 items pending”. Chromium content behaves like WebKit content.
Two bugs in the pass, both found only by running it: open -a Finder ~ is a
no-op when a Finder window is already open — the state the pass’s own
previous run leaves behind, so the second run reported a dead control and
thereby invalidated its own Electron row — and ELECTRON_CANDIDATES said
“Visual Studio Code” where NSWorkspace says “Code”.
The observer, wake= and this pass were then removed on the strength of
that result: notifications never arrive for the content this workload
targets, and the native-only win did not justify the surface. All three are
in git history (a60fa81 and its parents) should the question be reopened —
which is also where to start if a future macOS or Electron version is worth
re-measuring. A true Electron application was never measured; this was
Chromium the browser.
tools/uia_pass.py against Notepad on Windows 11 Home 10.0.26200, 26/26 on
four consecutive runs). Everything the AI-integration work added to
platform/win/uielement.py had been written against UIAutomationClient.h
on a Mac and had never executed; this is the pass that settled it. Every
previously-unrun vtable slot answers correctly — GetFirstChildElement 4 /
GetNextSiblingElement 6 (49 nodes with their real roles and AutomationIds),
get_DocumentRange 7, ExpandToEnclosingUnit 6 with TextUnit_Line = 3
(the caret’s line, and not the whole document, which is what a wrong unit
produces), and ElementFromPoint 7. set_focus() agrees with
HasKeyboardFocus — which was too weak a question, as the focus pass below
found: both were the element’s own opinion of itself. get_selection()
returns the selection, and the modal three-beat plus an idempotent
set_checked run end to end against Notepad’s Find UI.set_value measurement ai-integration.md §10 asks for, timed
against a real control: set_value 15–33 ms, paste 48–95 ms, keys
114–272 ms. All three work; the ordering matches macOS with a wider spread,
and none of it changes the paste, then keys default — speed is not the
axis that matters when the fastest is the one that fails invisibly.Does Windows set_focus() report a focus that never landed?
(2026-09-04, tools/win_focus_pass.py, 22/22, plus a browser probe, on
Windows 11 Home 10.0.26200.) It did, and not for the reason the question
assumed. Every HWND-backed scenario lands: a control in the foreground
window, in a background one, asked from a process holding no foreground
rights, disabled, clipped offscreen, in a minimized window, a label, a tab
item with no HWND of its own — all of them, and Windows even lets the focus
onto a disabled control and into a WS_EX_NOACTIVATE window. What lags is
the observer: GetGUIThreadInfo trailed a landed focus by 23–86 ms. That
gap is not the macOS bug in Windows clothing, though, because a keystroke
injected the moment set_focus() returned still arrived at the target —
the focus change and the key queue on the same thread, in that order.
The lie needs a provider that is not the HWND proxy. In an Edge page, a
<div> and a <p> both answered SetFocus with S_OK while the focus
stayed in the text field that already had it; Notepad’s WinUI status bar
does the same, which is what tests/test_win_focus.py now pins against a
real application. That is the shape a wrong action target has, and
set_text() on that answer types the caller’s data into whatever field the
user was last in.
The cheap fix — reading the already-declared HasKeyboardFocus — was
measured and rejected: an Edge field reports it True while the browser is
behind another window and the keyboard is elsewhere, which is exactly the
failure macOS’s docstring describes. So the answer comes from
GetFocusedElement compared with CompareElements (slot 3, newly pinned
against handles Win32 already knows apart).
set_focus() no longer answers at all. Returning a verdict was the
deeper mistake — the released code returned the HRESULT, and the first fix
here returned the landing, and both are one bool too few: there are two
honest verdicts —
the focus is on this element, or it is inside it — and the platform
layer cannot choose between them for the caller. Both are now named and
separately testable, on both platforms: has_focus() and
contains_focus(). set_focus() performs the act and returns None, so a
caller who forgets to check fails closed rather than open, which is the
shape of the bug this whole entry is about.
Choosing between them is the caller’s job, and the caller of record is the
action author. focus() and set_text() require has_focus() — there is
no list of roles allowed to write on an inside-answer, because such a list
is platform data (ComboBox, AXComboBox, and whatever the next
framework calls it), and inventing a portable vocabulary for platform data
is the thing this layer has refused to do since the element API existed.
The Action API exposes both questions instead: UINode.has_focus() and
UINode.contains_focus(), with the combo box written up in the authoring
skill’s quirks.md.
Refusing everything strictly is only reasonable because the delegating case
has a target that works. Measured: a Win32 ComboBox shows its Edit part in
the public tree with AutomationId '1001', fill.focus() on the part
answers True in 43 ms, and set_text() on it reads back as 'typed-inner'
on the part and on the combo box. So the advice “name the part” is advice
that works, not a shrug. The cost is real and worth stating: set_text()
aimed at a combo box worked in 2.3.0 (everything did — set_focus()
returned True unconditionally) and now fails after the full FOCUS_TIMEOUT.
What makes that failure survivable is that it says what happened.
contains_focus() is read for diagnosis and nowhere for permission: when
the strict check fails and the focus turned out to be inside the target, the
FillFailed names the element that actually took it — “the focus landed
inside it, on Edit (identifier ‘1001’) - write to that element if it is the
one you meant”, measured against a real combo box and a real page. It does
not say why the focus is inside: a control delegating to its part and a
container merely holding the focused control look the same from there, and
naming what took it serves both. Permission and diagnosis are
different uses of the same fact, and only one of them can put text in the
wrong field.
Containers stay refused by the same one rule, with no special case: with a
page field focused, the <div role=group> around it, the Document and
three Panes above it all answer contains_focus() true, as do the probe
window and the desktop root in the Win32 case — six levels of elements that
cannot take a keystroke.
The principled alternatives that were tried and failed measurement, since
they will occur to the next person too. IsKeyboardFocusable (slot 27) does
not discriminate: a top-level Window and the desktop Pane both report True,
and correctly so, since a window with no focusable child really does hold
the focus itself. “The value can be read back from the target” does not
either: a Chromium Document reports its URL as a value. And the delegating
family is smaller than it looks — a Win32 Spinner does not delegate (the
focus lands on the Spinner itself), and neither does a page’s <select>.
What this costs when the selector is simply wrong, measured through the
public path (find(name=...) on a page, then focus() / set_text()): a
named container is refused after the full FOCUS_TIMEOUT with
FillFailed(attempted=()) and nothing typed anywhere, where allowing
containment answered True in 7 ms and put the keystroke into a field the
action never named. The asymmetry is the whole argument.
The macOS half was written unverified, and the measurement found a
defect (2026-09-05, macOS 26.6.2, TextEdit). contains_focus() answered
False for every container — the exact opposite of the contract above.
The cause was one shared fallback. AXUIElementCreateSystemWide() lists
AXFocusedUIElement and AXFocusedApplication among its attributes and
then answers kAXErrorCannotComplete (−25204) for both — every read, with
the messaging timeout raised to two seconds — while the frontmost
application answers the same attribute instantly. (Which callers it
refuses was established later, and it is not everyone — see the issue #45
pass below. This measurement was taken in a probe process, and that is the
kind of process it describes.) Both predicates used that
read as their primary path and fell back to the element’s own AXFocused,
which answers has_focus()’s question and not contains_focus()’s. So
has_focus() stayed right by luck and contains_focus() never walked at
all: measured above a focused AXTextArea, the AXScrollArea and
AXWindow holding it both reported False.
MacFocusProvider.get_focused_element() has had the correct two-step
resolution since it was ported — system-wide first, then
NSWorkspace.frontmostApplication() — because this failure was already
known here. The predicates, written on a machine with no Mac, re-derived
the system-wide read without it. The fix is one resolution
(uielement.focused_element()) shared by both callers, and no AXFocused
fallback anywhere: when the focus cannot be read, False is the safe answer.
After it, the same probe reports contains_focus() true on the
AXScrollArea, AXWindow and AXApplication above the focused element,
with has_focus() true on the element alone.
The lesson is the one the Windows text layer taught: a second
implementation of a question the codebase has already answered is where the
known workaround gets left out. Pinned hermetically in
tests/test_mac_uielement.py — the front-application fallback, the
unreadable-focus case, and that neither predicate consults AXFocused.
Still unmeasured on a Mac: whether an AXComboBox delegates to an inner AXTextField the way the Win32 one does — if it does not, macOS simply never takes that path.
The payoff, measured after the fix: fill.focus() on a real field answers
True in 50 ms, and on a <div> spends the whole of FOCUS_TIMEOUT asking
again before answering False (1053 ms) — the retry loop 7f9edfa added
could not engage on Windows before, because the first ask always said yes.
set_text() on that element then raises FillFailed with an empty
attempted, and nothing is typed anywhere. No change to keyhac/core/.
One thing the pass cannot measure and now says so: every UIA call into a
window whose thread has stopped pumping blocks indefinitely — over 20 s for
from_hwnd alone, before set_focus is even reached. A hung application is
a hang, not a lie, and section I of the pass runs behind a watchdog because
a first run took the whole pass down with it.
Can Windows afford the focused element in the per-keystroke probe?
(2026-09-13, tools/win_probe_cost_pass.py, 4/4, Windows 11 Home
10.0.26200; issue #145.) No, and the decisive number is not the median.
macOS puts the focused element in its probe for one 0.107 ms
AXFocusedUIElement read, which is what makes #144’s design affordable
there; IUIAutomation::GetFocusedElement() had never been timed on its own.
Warm medians, 200 samples each, against the cheap tier measured in the same
loop on the same machine:
| in front | cheap tier today | GetFocusedElement |
read + compare | vs today |
|---|---|---|---|---|
classic Win32 (an EDIT) |
0.012 ms | 3.455 ms | 3.098 ms | 256x |
| Chromium (Edge, page input) | 0.013 ms | 2.652 ms | 3.106 ms | 238x |
| WinUI/XAML (Notepad) | 0.012 ms | 1.583 ms | 1.559 ms | 133x |
| a window pumping at 50 ms/message | 0.012 ms | 210.6 ms | 209.7 ms | 18,206x |
| a foreground window that never pumps | 0.012 ms | never returned (blocked past the 6 s watchdog) | — | — |
The last two rows are the finding. The cost belongs to the other
application, not to us: a window that merely pumps slowly puts 210 ms on
every key event, and a hung foreground window blocks the read for as long as
it stays hung — the same failure #144 is about on macOS, imported into the
platform that does not have it. Today it cannot happen: the cheap tier is
pure-local, GetWindowTextW deliberately does not message a window it does
not own, and it held at 0.012 ms with the hung window in front.
Two things the issue expected turned out backwards, which is why it was
asked as a question. The comparison was supposed to be the second
cross-process call, Windows having no CFEqual: measured, CompareElements
on two already-fetched elements is 0.008–0.019 ms and GetRuntimeId (slot 4,
newly pinned) 0.017–0.040 ms — both client-local, because a UIA element
carries its runtime id from the fetch. It stops being local when one side is
stale: against an element whose process had exited, the compare took 2.35 ms
and answered “cannot say” (None, not a wrong False — which is the reason
_same_element returns a tristate). And the expensive provider was not the
Chromium one — the classic Win32 EDIT was the slowest of the three, so
there is no “only exotic frameworks are dear” reading available.
Verdict: the limitation is accepted and written down rather than fixed.
focus_path_pattern= is best-effort on Windows — re-read when the window,
the focused child HWND or the title changes, and blind to focus moving
inside one window (list items, tab items, and every in-page move in
Chromium / Electron / WPF / WinUI, where there is one HWND and no focusable
children at all). app=, title= and class_name= are exact: the same
HWND is the same process, and the focused HWND determines the class name.
Documented in configuration.md,
define_keytable()’s docstring and platform/win/focus.py’s. An action
that needs the element as it is now still calls get_focused_element(),
which pays the 1.6–3.5 ms once, deliberately. What a revisit would change is
the detector rather than the call — a pushed focus event asks nobody
anything, on either OS — which is issue #150.
Which application is in front, measured both ways (2026-09-13, macOS
26.6.2, tools/mac_focus_pass.py, three runs / ~900 samples / 12 driven
switches and several real ones). Issue #45 reported
keymap.get_active_window() naming VS Code while the operator was in
Claude, and asked whether MacFocusProvider.get_focus’s two uncrossed
sources — NSWorkspace.frontmostApplication() for app_name, the
system-wide AXFocusedApplication for element — can name different
applications.
The precondition nobody had checked was which process the reading was
taken in, and it decides the answer. The system-wide element refuses
AXFocusedApplication instantly (0–1.5 ms, and still instantly with the
messaging timeout raised to two seconds) in a process that has never created
an NSApplication, and answers a process that has. That is the whole
difference: NSApplication.sharedApplication() alone flips the same read
from −25204 to success in the same process. So the a69211f reading above
describes bare scripts and pytest runs, not Keyhac — inside Keyhac the
primary read is taken, the fallback is dormant, and the two sources really
were independent. The fallback still has to stay: it is the path every test
and every tool takes.
No divergence was caught. In every sample where the AX read succeeded,
the two named the same process — across driven switches sampled 150 ms
apart, real switches, and a screen lock. Nor was the issue’s second
observation reproduced: no sample had more than one application claiming
AXFrontmost.
Two ways the AX read fails, and they mean different things. After the
full messaging timeout (~7% of samples on an idle machine) — the read is
served by the front application, so a front application busy for longer than
the cap cannot answer it. And fast, 11–20 ms, while the focused application
is exiting: there AX has already let go and NSWorkspace has not, so the
fallback names a process that can no longer be reached. That transient is
the same shape as issue #44’s destroyed-element reports, and it is a
staleness, not a disagreement: both halves of the Focus still name the
dying application.
What changed anyway is the structural half the issue called real regardless:
one resolution, uielement.focused_application(), shared by get_focus(),
focused_element() and get_active_window() — which asked the same
question a third time, in the call the issue was reported against. app_name
is now the name of the process the element belongs to, so the two cannot
disagree by construction, which matters because app_name is what
define_keytable(app=...) matches on and the table it selects then acts on
element. Pinned in tests/test_mac_focus.py and tests/test_mac_uielement.py.
The macOS cheap tier (2026-09-13, macOS 26.6.2, issue #144). Every key
event rebuilt the focus path from scratch: 83 AX reads per get_focus()
against VS Code, 81 of them _build_path’s AXParent walk, and
_check_focus_change runs on key down and key up — 166 round trips per
keystroke, with no early-out for modifier keys, unbound keys, pass-through
keys, or a configuration with no key tables at all. Verified identical on
both sides of #45 (HEAD 420df99 and its working tree), so the structure
predated that change rather than arriving with it.
The milliseconds were never the argument — warm, that is ~2.5 ms. Every one
of those reads is answered by the focused application’s main thread
inside the event tap callback, which is why hook.py carries
kCGEventTapDisabledByTimeout handling and a once-per-second re-enable.
tools/mac_focus_pass.py caught AXFocusedApplication alone hitting the
full 100 ms messaging timeout in ~7% of samples with a Python application in
front.
Windows has had the answer since it was written — win/focus.py’s probe,
two HWNDs and a title, all local Win32 (GetWindowTextW does not message
another process, so the tier cannot be stalled by a hung application). macOS
never got the layer. It has one now: (frontmost pid, AXFocusedUIElement
ref, window title), four reads, compared with CFEqual for the element.
Measured after: 85 reads on a miss, 4 on a hit, 8 per keystroke
against 166, median get_focus() 2.492 ms → 0.141 ms.
Verified live, one probe component at a time
(make mac-focus-pass ARGS=--verify-probe, which scripts a throwaway
application so the run needs nobody at the keyboard):
[ 0.4s] new Focus - app='Python' title='probe one' focus=AXTextField()#80007
[ 2.3s] new Focus - app='Python' title='probe one' focus=AXTextField()#80039
[ 4.3s] new Focus - app='Python' title='probe two' focus=AXTextField()#80039
The second row is the same application and the same window title with only
the focused element changed — the case GUITHREADINFO.hwndFocus cannot see,
so this probe is the more accurate of the two, not a weaker port (#145). The
third is the same element with only the title changed, which is what title=
matches on. 78 calls, 5 rebuilds: 94% answered from the cache.
The title is read only to compare and never reaches the Focus:
window_title still comes out of the path walk, transliterated through
FOCUS_PATH_TRANS_TABLE, because every title= pattern is written against
that spelling and a raw title used as a value would break each one
containing a bracket. What the probe still cannot see is an ancestor’s
title moving under a focus_path_pattern while the element and window title
both stay put — narrower than the gap Windows has shipped with.
The same issue’s other half was a staleness bug, not a cost. The engine
re-merged the key tables only when focus.path changed, and the path is None
whenever the focused control cannot be read — which is exactly how an
application busy past the messaging timeout answers. Moving between two such
applications left the key unchanged at None and the first one’s app= tables
active in the second. The trigger is now every field a FocusCondition
reads. custom_condition_func is not in it and cannot be: it receives the
whole Focus and may read anything, so it keeps what it has always had —
re-evaluation when the key moves. Pinned in tests/test_keymap.py and
tests/test_mac_focus.py.
Left measured but unchanged: get_focus’s second read is uncapped. The
messaging timeout is set on the system-wide element, which bounds only the
read made through it — the application element it hands back carries the
system default, so AXFocusedUIElement and the whole _build_path walk are
unbounded on the key dispatch path. Observed at 3–31 ms against healthy
applications, so there is nothing to see on an idle machine; against a hung
one the existing comment’s promise (“a hung app must not stall key
dispatch”) is not kept. focused_application() takes a timeout for it and
get_active_window() passes the cap it already had; get_focus() does not,
because bounding a read it has never bounded changes what a momentarily slow
application produces and wants its own measurement.
The bug the pass caught is in fill.py, not in the Windows layer.
_paste holds the clipboard swapped until confirm() answers, precisely
because restoring as the keystroke goes out races the target’s read of the
pasteboard. With verify=False there is nothing to confirm, so confirm()
returned immediately and the guard evaporated: the document received the
shell command the operator had copied an hour earlier — the documented
failure, reproduced through the one door left open. Now an unverified paste
holds for PASTE_SETTLE and says in the log that it is guessing, with the
ordering pinned in tests/test_fill.py.
SelectionItem, and the first action to run on both platforms
(2026-08-07). Porting examples/actions/mac/snapshot_settings.py to Windows
stopped before it reached a selector: a Win32 TabItem supports no Invoke,
no Toggle and no Expand — get_action_names() returned [] — and has no
value, so neither selecting a tab nor asking which tab was current could be
expressed. SelectionItemPattern (10010) now provides both, pinned against
TCM_GETCURSEL on a real SysTabControl32 built in the test
(tests/test_win_focus.py), which is the control’s own answer and is not
reachable through UI Automation — so it cannot agree with a wrong slot by
accident. examples/actions/win/snapshot_settings.py then walked Mouse
Properties’ five tabs live and wrote 15 values to JSON, leaving the
originally-selected tab selected.Two things the pass itself got wrong, both worth keeping in mind for any Windows UI harness:
FindWindowW("Notepad", None) names that — on the first run, the real
~/.keyhac/config.py, whose buffer every write then replaced. Nothing
reached the disk, but a harness that can overwrite the file it is testing
against is a harness with a bug in it. It now opens a scratch file, locates
the window by its title, identifies the text element by a sentinel string
only this pass writes, requires that element to hold keyboard focus, and
refuses to write at all if any of that does not line up.It looked for a role where it should have looked for a capability. The
three-beat waited for a CheckBox; Windows 11’s Find panel has none, and its
“Match case” is a MenuItem one press further in, behind “More options”.
Searching for an element with a ToggleState finds it whatever it calls
itself — the Windows form of the macOS lesson in the authoring skill, that a
control is defined by what it can do rather than the role it reports. The
search has to be scoped to the panel as well as by capability: run against
the whole window it finds the formatting toolbar’s Bold button, which
also has a ToggleState and has nothing to do with Find.
tools/text_pattern_survey.py). Notepad had been the only Windows evidence
for §6’s cheap rung, and it is a weak proxy — one document surface, no
renderer. Windows Terminal returns 366 characters of scrollback from a
Text element with get_line_at_caret() giving one line of it; VS Code
exposes the editor as an Edit named for the open file. Both answer, so the
read-everything-and-match path holds on Windows as it does on macOS.
Notepad runs alongside as a control, because a survey that finds nothing
in VS Code cannot otherwise tell “VS Code exposes no text” from “the probe is
broken” — and on the first two runs the probe was broken, so this earned
itself immediately.set_manual_accessibility(); it needs a retry. The mechanism was not
isolated — the process was the operator’s own VS Code and could not be
restarted cold — but the observation repeated and the consequence is the same
either way.wt.exe treats ; as its own subcommand separator, so a PowerShell
-Command containing one is split into extra tabs and never arrives intact;
use -File. And wt --title holds only until the hosted program names the
window, which PowerShell does immediately, using its own command line — which
contained the survey’s sentinel, so the terminal’s window matched the next
target’s title search and got measured and reported as VS Code. Set the title
from inside the shell, and give every target its own token.Notepad 11 drops and reorders injected input, and this is the target’s doing,
not ours. hello-keys arrived in its text box as helloke-ys; a Ctrl-V
came through as a bare v; and an injected Ctrl-V is silently dropped
outright often enough that the pass retries it. The same strings down the same
code path — including with a real hook installed and through InputContext,
which is what fill.py uses — land intact in a plain Win32 control 30/30
(tests/test_win_send_text.py and a scratch probe), so the reordering is
WinUI’s, not SendInput’s and not the hook’s. Two consequences: keys is not
trustworthy against XAML editors, which is an argument for the existing
paste-first default; and every one of these arrived as a loud failure
because set_text reads back what it wrote. That rule is what turned a
silently corrupted document into a FillFailed naming the text it actually
found.
macos_app/ built, signed, notarized and run live end-to-end (tap
installs under the bundle identity, template config created, SIGINT quits
cleanly); windows_app/ passed end-to-end, 11/11 in tools/bundle_pass.py
(tool-window styles, the saved frame restored and the moved one written back,
a poisoned off-screen frame rejected onto a monitor, clean quit on the tray’s
teardown path, cross-process instance guard, no keyhac-error.log), with the
tray icon + menu and the console’s log pane / hook checkbox / log-level
dropdown passed by hand alongside it.tests/test_win_typing_load.py, Windows 11 in a VM): at a
sustained 60 keys/s the hook callback runs p50 ≈ 1.0 ms / p95 ≈ 2.1 ms; a
200-event unpaced burst is p50 ≈ 0.8 ms with every keystroke translated and in
order; and with every core busy in other processes the numbers barely move
(p50 ≈ 1.4 ms). Typing feel is not load-sensitive in the ordinary sense.ThreadedAction doing heavy Python work
looks like — pushes the callback to p50 ≈ 64 ms / p95 ≈ 131 ms / max ≈ 500 ms,
i.e. past the 300 ms LowLevelHooksTimeout. sys.setswitchinterval(0.001)
roughly halves it (p50 ≈ 42 ms, max ≈ 295 ms) but does not remove it. Config
authors should keep CPU-bound Python out of ThreadedAction, or accept that
Windows may drop the hook and check_health() re-install it.InputContext from a worker blocks typing for exactly as long as it is held
— it takes the same RLock the hook callback needs. Measured: a 50 ms hold
produces a ~50 ms callback. A hold longer than 300 ms will get Keyhac unhooked.ansi and jis vk tables match kbdus.dll
and kbd106.dll exactly on every physical key position where the two keyboards
differ — the semicolon, colon, atmark, caret and bracket keys, and the two JIS
backslash keys (¥ and ろ), which a US 101 renders as one. This is
hardware-independent; the GetKeyboardType(0) == 7 detection is the one
part that needed a real JIS keyboard, and it was confirmed on one by hand
(2026-08-07). Both halves of the layout story are now closed: the tables
against the keyboard-type DLLs, the detection against the hardware.edit_config on Windows: WinAppControl.edit_file → ShellExecuteW run
live, 8/8 — default editor, explicit editor, a path containing spaces opening as
one file (the quoting), an unresolvable editor logging a warning instead of
raising (ShellExecute code 2), the full Keymap.edit_config() chain, and the
deleted-config-recreated-from-template path.
Candidate-window streaming, macOS (PR #125, real MacOSBackend, not the
memory one). The measurement that mattered was of the delivery, not the walk:
a bare tick callback runs at the idle rate, 10.0 Hz measured (median gap
100.0 ms), so _drain’s 2 ms slice is a 2% duty cycle. End to end, same window
and sources, before → after moving the accessibility walks to a worker:
Chrome menus 11,723 → 257 ms (212 rows), VS Code menus 4,724 → 213,
iTerm2 menus 7,420 → 311, Chrome controls 9,544 → 342. First row 130 → ~60 ms.
A 212-row fill is 6 _append calls rather than 212. Dismissed 40 ms into a
walk: 0 rows landed afterwards and no worker thread survived.
What made the worker safe was measured rather than argued. A frozen target
blocks only the worker: against an application deliberately stopped on its
main thread, an AX call sat in the worker for 1.51 s — returning
kAXErrorCannotComplete on AX’s own ~1.5 s messaging timeout — while the main
thread’s Python throughput did not move (4.91M vs 5.0M iterations per half
second). The contention runs the right way round: a main thread busy with
Python starves the worker (149 AX calls/s against 24,400), not the reverse.
Cost to the main thread with the walk flat out: a hook-sized piece of work
goes from 0.06 ms median to 0.19 (p95 0.20, max 0.32). One worker is the
right number: six applications on six threads took 948 ms against 935 ms for
the same six in a row — the GIL is the ceiling, not the IPC wait. No
autorelease pool needed: RSS plateaus across 25 repeated walks with and
without one.
The rule that had ruled all this out was one level too broad — platform/base.py
says AX into our own process off the main thread SIGTRAPs, and design-notes
had generalised it. Both now say so.
The chooser’s keystrokes off the hook callback, macOS half (PR #126, whose
own numbers were all measured on Windows and which says so). Verified here on
real hardware — real MacOSBackend, real Keymap, real ChooserWindow, keys
fed the way the hook feeds them — 7/7: keys are queued while the callback runs
and not acted on there; they land in order (alp from A, L, P) and filter;
five in a burst all land; a closing key is not followed by one acted on after
it; dismiss() drops what was queued. The callback is 0.021 ms median with
8,000 candidates in the window.
The macOS before figures, for comparison with the Windows table in #126 — and the reason the two look so different is row length, not the platform:
| candidates | 45-char rows | 200-char | 800-char |
|---|---|---|---|
| 250 | 0.7 ms | 1.3 ms | 4.0 ms |
| 1,000 | 1.5 ms | 3.9 ms | 13.2 ms |
| 4,000 | 5.5 ms | 15.0 ms | 53.3 ms |
| 8,000 | 10.4 ms | 30.6 ms | 109.3 ms |
So Windows’ 259 ms at 8,000 is not anomalous. macOS had more headroom than
Windows did — kCGEventTapDisabledByTimeout is less eager than a 300 ms
LowLevelHooksTimeout — but the shape is the same on both, and the deferral
is correct and harmless here. What makes deferring safe is not a macOS
property: Keymap._on_key_down returns True for a grab unconditionally,
without consulting the modal handler’s return value, so the callback was
never deciding anything.
Candidate-window streaming, Windows (PR #125’s other half, real
WindowsBackend, targets addressed by HWND so the same window is measured on
every repeat). The tick is a genuine 60 fps here, not macOS’s idle 10 Hz:
median gap 15.935 ms over 40 intervals (62.76 Hz), which makes the 2 ms
slice a 12.55% duty cycle. The improvement that predicts — about 8x — does
not appear, and the reason is worth keeping: the slice is smaller than one
row costs. A single next() on the controls walk is a median 2.77 ms
(Explorer), 3.19 (VS Code), 3.39 (Chrome), and 84-89% of rows exceed the
2 ms budget on their own. _drain checks its deadline after appending, so
a slice that can only afford one row still takes one: the old path ran at
roughly one row per frame, ~16 ms/row, whatever the duty cycle said. Against
rows x 15.9 ms: Explorer 96 rows predicts 1527 and measured 1721; Chrome 36
predicts 572 and measured 723. The ceiling on the ratio is therefore
tick / per-row cost, ~15.9/5.6 ~= 2.8x.
| window (rows) | walk alone | before | after | ratio |
|---|---|---|---|---|
| Explorer, 5-file folder (96) | 517 ms | 2143 ms | 646 ms | 3.3x |
| VS Code (202) | 1296 ms | 5016 ms | 1637 ms | 3.1x |
Chrome, about:blank (36) |
216 ms | 723 ms | 293 ms | 2.5x |
| Notepad, WinUI (22) | 144 ms | 367 ms | 228 ms | 1.6x |
| XeFM, PuiKit (10) | 32 ms | 65 ms | 78 ms | 0.83x |
First row is 47-162 ms after and 28-198 ms before — the old path was never slow
to start. XeFM is the honest counter-example: 10 rows at 0.44 ms each fit
several to a slice, so the drain was never the bottleneck and the worker’s
cross-thread dispatch costs slightly more than it saves. The win scales with row
count, not with tree size. MenuItemsSource yields nothing on Windows and
get_attribute_values is a plain loop here, so all of this is the worker and
nothing else. A Settings (UWP) CoreWindow yields 0 named controls; not
investigated.
These are the numbers the CacheRequest question was waiting on: the per-row
figures above are its sizing — ~5.6 ms mean per reported row against a 15.9 ms
frame.
Cost to the main thread, hook-sized work every 10 ms, 200 samples: idle
baseline 0.38 median / 0.75 p95, a worker walking with rows discarded 0.35 /
0.68 — indistinguishable from idle — and the full background path 0.55 / 5.41.
The tax is _append re-ranking each batch, not the UIA traffic. (max is not
trustworthy at this resolution: the idle baseline itself threw a 15.10 ms
outlier.) A frozen target blocks only the worker, same as macOS: against a
window that stops draining its message queue, ElementFromHandle sat in the
worker for 24,746 ms — returning the instant the target resumed — while main
thread throughput held at 99.9% of baseline. Note there is no timeout, and
_stop_background’s event is only checked between rows, so closing the chooser
does not free a worker wedged inside a call. It is a daemon thread, so it never
blocks exit; repeatedly opening the chooser against a hung application leaks one
thread per invocation. Not addressed.
The COM apartment the walk runs in, Windows (PR #126). The suspected failure
does not exist on this OS, and looking for it found a different one. No failure
could be provoked: 65,555 HRESULT-returning COM calls from uninitialised
workers into Explorer, Chrome, Notepad, VS Code, Settings and XeFM — including
six concurrent workers sharing the main thread’s interface pointers — returned
not one negative HRESULT. Every vtable return was inspected by wrapping
_com_call, not just the ones callers look at. CoGetApartmentType says why: an
uninitialised worker reports MTA / IMPLICIT_MTA, Windows 8+ placing a
thread that touches COM without initialising it into the process-wide implicit
MTA — the apartment Microsoft recommends for UIA clients anyway.
The reachable bug is the ordering. Before anything in the process touches COM
a fresh thread reports CO_E_NOTINITIALIZED, and get_automation() initialises
its own thread as an STA. Measured: a worker reaching it before main()
becomes the process MAINSTA, leaving the cached process-wide automation
pointer bound to an apartment that dies with that thread. Only ordering stops it
today. Fixed by claiming COINIT_MULTITHREADED up front, after which the same
call returns RPC_E_CHANGED_MODE — already accepted.
What the fix does not reach, with the evidence that sizes it: element
pointers are made on the main thread and called from the worker unmarshalled.
Asked directly, IUIAutomationElement implements IAgileObject — the bulk
of the traffic is legitimate by declaration, not by luck. IUIAutomation and
IUIAutomationTreeWalker do not (E_NOINTERFACE; the root’s IMarshal
names unmarshal class 0000033a-..., not the free-threaded 0000001b-...), and
the worker calls both — the root once per walk, the walker once per node. If a
failure ever appears, try a per-thread automation instance and walker, not
CoMarshalInterThreadInterfaceInStream. Untested: an elevated target.
regedit refused to launch (WinError 740) and nothing elevated had a window,
so the one case where UIPI could still produce the predicted RPC_E_* has not
been exercised.
The chooser’s keystrokes off the hook callback, Windows half (PR #126, whose
numbers these are). Two warnings — 204 ms then 344 ms, both vk 67 — with two
separate causes. Migemo’s dictionary, read lazily on the first query long
enough to reach the engine: _load_engine’s docstring budgets ~50 ms, measured
it is 190 ms alone and 267 ms through compile(). Not one character’s fault
— MIN_LENGTH is 3, and measured, a one- or two-character query never loads the
engine at all (0.04-0.19 ms, engine untouched); it lands on the third keystroke,
once. And filtering, which is linear in the candidate count: 250 rows 17 ms,
1,000 37 ms, 4,000 131 ms, 8,000 259 ms, nearly all of it the ranking sort and
needing no Migemo to get there. That reaches the warning at ~6,000 rows and
LowLevelHooksTimeout at ~9,000. After moving the work off the callback, the
callback is 0.05 ms whether the window holds 250 candidates or 8,000, and the
dictionary read goes off it too, so both warnings go. Worst single query, found
by brute-forcing 400 three-letter romaji against the real 258-entry clipboard
history: shi, whose Migemo regex is 1,772 characters — hit 52 ms + rank 18 ms.
_UnionMatch.spans runs base and Migemo unconditionally where hit short-
circuits, so rank pays the finditer a second time; not fixed.
The chooser could not be resized or moved on Windows, and it was PuiKit’s
(puikit #133; no Keyhac-side change). _on_mouse_down called
SetCapture(self._hwnd) — the main window — while also running for a secondary
window’s messages inside _window_scope, so a press in the chooser handed the
capture to the console and every later move and the button-up went with it.
Capture is what keeps a drag alive once the pointer leaves the window it started
in, which is exactly what a frameless window’s own resize edge and drag handle
are: dragging an edge outwards leaves the window within a few pixels. macOS
routes a drag to the window that took the mouse-down and has no capture to aim
wrong, so this was Windows-only. Measured with real SendInput, before → after:
a 90 px corner drag resized by nothing → 1224x780 to 1324x880, and a 90 px handle
drag moved (0, 0) → (90, 90). The diagnostic trap worth remembering: posting
the messages by hand works, because that skips the OS delivery the capture
governs; it reproduces only with SendInput. WM_MOUSELEAVE tracking had the
same mistake and moved with it.
describe_screen content-access hint named the wrong cause (issue
#56), and the pass that settled it needed two applications the machine was
not already running. The trick worth keeping: a throwaway instance of a
Chromium application is the only way to see the “never asked” state, because
the switch is per-application and, once built, a Chrome tree does not come
back down. Google Chrome --user-data-dir=<tmp> gives one directly; VS Code
needs env -u ELECTRON_RUN_AS_NODE (the integrated terminal exports it, and
with it set the app binary parses its arguments as node and rejects them),
and a short --user-data-dir — its IPC socket path has a 103-character
limit, which a scratchpad path silently exceeds. Both instances then need
closing; a stray one keeps the profile and the window.
The measurement itself is in doc/dev/ai-integration.md §10; the
reproduction that mattered was a local server that withheld a page body for
six seconds, which turned a 50 ms race into a state that could be read at
leisure.Could focus changes be pushed instead of polled, on macOS? (2026-10-17,
tools/mac_focus_push_pass.py, macOS 27.0.1; issue #150.) An AXObserver
on the front application covers every component of the cheap probe, but it
is late often enough to be wrong, and draining it does not close the gap.
Coverage. Registered on the application element, each change the probe
sees raised its own notification, and none went unannounced: a focus move
inside one window → AXFocusedUIElementChanged; a window rename →
AXTitleChanged (so registering it on the application does deliver its
windows’); a second window taking focus, and closing →
AXFocusedUIElementChanged + AXFocusedWindowChanged +
AXMainWindowChanged.
Registration is the switch-path cost the issue predicted: 20–43 ms per
application (four AXObserverAddNotifications, median 25 ms over the 11
running regular applications), paid on every application switch. Against an
application that has stopped pumping it is four messaging timeouts — 1004 ms
at 250 ms each — and then it has not taken: every add answered
kAXErrorCannotComplete, and once the application recovered, focus moves in
it raised nothing. A push design needs a retry, with polling in the
meantime.
Ordering, the one that decides it. Tab into the pass’s own two-field window, then F13 once the Tab has passed a session tap and a gap has elapsed; each F13 the tap sees is classified against an AX poll taken in the same callback. 30 rounds per gap:
| gap after Tab | idle: stale / 30 | busy: stale / 30 | busy: left stale after the drain |
|---|---|---|---|
| 2 ms | 10–15 | 11–12 | 11–12 |
| 5 ms | 8–11 | 15–17 | 7–8 |
| 10 ms | 3 | 18–19 | 6–7 |
| 20 ms | 3–8 | 30 | 5 |
| 50 ms | 0 | 30 | 0 |
“Stale” is a key that the poll says landed on the new focus and the observer had not yet reported, so push would dispatch it against the old one, and today’s probe gets it right. (At 0 ms, and for the rest of each row, the application had not processed the Tab yet, and a poll is as wrong as push.) Tab passing the tap → first notification: median 13–15 ms, p95 35–42 ms, max ~50 ms. Idle is Keyhac between keys, run loop free. Busy services only the tap, so notifications queue. The drain the issue proposed (run the observer’s source alone, in a private run loop mode, at the top of the tap callback) delivers what has been queued, which fixes most of the busy column. It does nothing for idle, because there is nothing to deliver yet: the application moves its focus first and sends the notification later. A key typed within ~50 ms of a focus-moving key can be dispatched against the wrong focus, which is inside the range of key rollover. Roman input and the operator’s Japanese IME gave the same table.
Three harness lessons, each of which produced a clean-looking wrong answer
first. A throwaway application that spins NSRunLoop services sources but
dispatches no NSEvent, so posted keys never reach its fields (app.run()
does). The follow-up key must not be a printing one: once an x had been
typed into a field, later Tabs stopped moving focus and every row read 100%
“early”. And the gap must be pumped, not spun: a listen-only tap still holds
the event until its callback has run, so busy-waiting held the Tab back from
the application for the whole gap.
Not measured here: section D (--only-watch --watch N) follows real
applications and counts probe changes no notification explains. It needs
someone using the machine, and the unattended run saw nothing.
Could focus changes be pushed instead of polled, on Windows? (2026-10-16,
tools/win_focus_push_pass.py, 6/7, Windows 11 Home 10.0.26200; issue
#150.) The layer question the issue turned on came out yes: WinUI/XAML
(Notepad) raised the legacy EVENT_OBJECT_FOCUS for 20/20 UIA SetFocus
moves, classic Win32 and Chromium for 20/20 Tabs each. Chromium did so on
the cold pass too, before anything had asked Edge a UIA question; a machine
where nothing has ever turned Chromium’s accessibility on may differ.
Registering three system-wide hooks costs 0.24 ms and does not wait for a
hung foreground window. Latency, injection to first event (median / p95):
classic 9.0 / 27.5 ms, Chromium 3.6–4.1 / 10–11 ms, WinUI 10.3 / 42.7 ms.
Ordering, on the classic window only (GUITHREADINFO is ground truth there
and nowhere else): 26 of 120 F13s saw a moved focus with no event
delivered. Unlike macOS, the drain works here. PeekMessage(PM_NOREMOVE)
at the top of the hook callback delivered the queued event for 25 of the 26.
The one left was at a 2 ms gap.
What was decided from the two passes: no push on either OS. On macOS
the notification trails the focus by 10–50 ms, and nothing on our side can
fetch it early. On Windows the event source is good, but it would only
decide when to re-read, and an event that arrived recently is no proof
that a re-read can be skipped. Combining an event with a poll is the
complexity without the guarantee. The question #145 asked, whether
GetFocusedElement is affordable per key, is open again for a reason #145
did not have. Its decisive row was the hung window that never returned,
and since #171 every UIA call is capped at 250 ms, with the same
cut-short reuse macOS has. What is left is the median (1.6–3.5 ms) and
applications that are slow but under the cap, which are accepted as the
application’s fault. So Windows reads the focused element on every key
event, as macOS does.
Side effect worth knowing before a run: starting notepad.exe restores
Notepad’s previous session, so a tab of an existing file reappeared. The
pass only moves UIA focus in it, never types, and the file was left
unmodified.
Does the release run on macOS 12? (2026-10-21, issue #270, Keyhac
2.6.0 release DMG, macOS 12.7.6 in a Tart VM from
ghcr.io/cirruslabs/macos-monterey-vanilla, on an M5 host running macOS
27.) Yes. Gatekeeper accepts the notarized app, and the launcher,
the embedded Python and every import come up with no dyld or import
error. The menu-bar icon appears, the console opens and shows key events,
and the template config’s remaps work. 13 and 14 were not run: they are
only worth running if 12 fails. The bundle built afterwards from the fix
branch (floor 12.0, thinned to arm64 by #274, the icon below) launched
there too, with the hook installed and the config loaded.
The one real bug: Keyhac’s icon was noise in the Accessibility list.
Monterey’s IconServices does not read the PNGs make_icons.py wrote into
icp4/icp5, and those are the slots it uses for 16 and 32 pt at 1x.
Larger sizes, and every size at 2x, were fine, and NSImage decoded the
same file correctly, so only something drawn through IconServices shows
it. The icns now has the ic07-ic14 slots only, and the system scales
down from them. The permission messages also named System Settings,
which macOS 12 calls System Preferences, with the pane named the other way
round; they now name whichever the running OS has.
Three things about the VM, none of them Keyhac’s. The authorization UI
crashes in the guest (System Preferences aborts on the lock, and
UserNotificationCenter crashes, so the Accessibility prompt never
appears), so SIP was disabled from recovery to get the permission
through. The guest keyboard is a generic USB one with no Fn, because
Virtualization.framework’s Mac keyboard needs a macOS 14 guest. So the
remaps were driven through define_modifier("RCmd", "User0") in place of
the template’s Fn. And the default 1024x768 pt display is unreadably small
in recovery; tart set --display 1280x800px for recovery, a smaller
point size for normal boot.
macOS 11 cannot be run this way: Apple silicon virtualizes 12 and later
only. Rather than keep a floor nobody had run, MACOS_MIN_VERSION went
from 11.0 to 12.0.
And on the newest macOS, in a VM? (2026-10-21, Keyhac 2.6.0 release
DMG, macOS 27.0 (26A428) in a Tart VM from
ghcr.io/cirruslabs/macos-golden-gate-vanilla:27.0, running next to the
macOS 12 one.) Yes. Gatekeeper accepts it as Notarized Developer ID,
the Accessibility prompt appears and the grant goes through System
Settings, and the menu-bar icon, console and the template config’s
remaps all work. This guest has a Mac keyboard, so Fn is real and the
template runs unmodified. The pair of VMs is the standing way to check
the floor and the newest macOS before a release.
The image needed two things before its result meant anything. Gatekeeper
comes up allowing the App Store only (the template’s
spctl --global-disable is left half-done on 27), so every Developer ID
app is rejected with “lack of matching active rule”. Fixing it takes
sudo spctl --global-enable plus “App Store & Known Developers” in
System Settings; 27 no longer takes that from the command line. And its
44 GB disk filled within minutes from the macOS update downloading in the
background, so turn automatic downloads off first.
Does HTTPS go through the OS trust store in the bundles? (2026-10-25,
issue #279, main at d208836. macOS 27.0 in the Tart VM above, with no
python.org Python. Windows 11 Arm in VMware Fusion, driven over SSH as
described in “Driving a Windows VM from the Mac over SSH”.) Yes, on
both. The check from the issue ran at config load: ssl.SSLContext is
truststore’s, pypi.org is fetched, and both eMudhra test hosts
(dv-g3b-emudhra and dv-g3b-aaa-emudhra at we-have-a-problem.com) are
refused. The control was the bundle’s own Python run with -I, without
the injection. On macOS it fails every host, pypi.org included,
because the CA file it looks for is python.org’s, outside the bundle. On
Windows it accepts dv-g3b-aaa-emudhra.
The refusal reads differently on each. Windows says “The certificate is revoked.” macOS 27 says the certificate “is blocked”, where the development Mac had said “revoked”. The guess is that Apple’s own blocklist now catches these hosts before the revocation check does. The issue’s check therefore marks the macOS refusals WARN, not PASS. Both are refusals of the certificate itself, which is what the check is about, and neither is an unknown-issuer failure.
The whole suite, desktop tests included, in a VM on each OS (2026-11-01,
issue #293, make test-vm. macOS 27.0 in the Tart image
qa-mac-2026-10-31-2; Windows 11 Arm in VMware Fusion from the snapshot
QA-2026-11-01.) Both clean. macOS: 1503 passed, 23 skipped.
Windows: 1582 passed, 101 skipped. Every skip is the other OS’s test or a
platform difference (POSIX mode bits, PuiKit staged rather than
installed). These are the first full runs of the test_mac_* and
test_win_* tests from a clean state rather than on a development
machine.
The Notepad tests failed in the VM until three things were found, none
of them Keyhac’s. Notepad crashed within seconds of starting, because
the suite’s empty home (#308) was its USERPROFILE. That looked at
first like an application too slow for the 250 ms UI Automation bound,
then like a first window that goes away, and then like a broken
snapshot. A Notepad that did not crash was the classic one, not the
packaged WinUI one the status-bar test is written for, though the same
notepad.exe typed in the guest’s PowerShell opened the packaged one;
the tests now start the packaged app by its app ID. And a desktop just
signed in to has no foreground window, which one test had depended on.
On the way the Windows image moved to a powered-off snapshot, so each
run boots it (quality-loop’s guest layer waits for the automatic
sign-in).
launch= by Start menu name (2026-11-05, issue #319, make test-vm.
Windows 11 Arm in VMware Fusion from the snapshot QA-2026-11-03.) The
COM scan of shell:AppsFolder matches Get-StartApps exactly over 74
entries. Calculator (packaged), Character Map (known-folder path), Remote
Desktop (explicit app ID) and Python (absolute path) each start by display
name through shell:AppsFolder\<parsing name>. A parsing name that does
not exist raises FileNotFoundError within 0.01 s, which is how a stale kept
listing is noticed. The scan took 436 ms the first time in the process and
about 150 ms after that, in emulated x64 Python. A Store application
coexisting with a same-named command on PATH is covered by the scripted
tests only.Windows on Arm: the x64 build under emulation (2026-11-05, issue #318,
tools/win_hook_latency_pass.py, Windows 11 Arm 10.0.26300 in VMware Fusion
on Apple Silicon, 4 logical processors, snapshot QA-2026-11-03, the same
Python 3.14.10 from python.org as x64 and as ARM64 - the ARM64 one from
NuGet’s pythonarm64, in the same VM.) The whole of _hook_proc, in ms, the
real hook, engine and focus provider, with other processes’ windows in front:
| Keys, target | x64 emulated p50 / p95 / max | ARM64 native p50 / p95 / max |
|---|---|---|
| First key after a focus change, Win32 | 5.1 / 10.0 / 10.0 | 5.0 / 6.5 / 6.5 |
| First key after a focus change, Notepad | 4.7 / 6.5 / 6.5 | 5.0 / 6.5 / 6.5 |
| First key after a focus change, Edge | 5.1 / 37.1 / 37.1 | 5.6 / 9.8 / 9.8 |
| 30 keys/s, Win32 | 1.2 / 4.7 / 29.5 | 1.2 / 4.2 / 11.8 |
| 30 keys/s, Notepad | 1.4 / 4.6 / 6.0 | 1.2 / 4.5 / 6.1 |
| 30 keys/s, Edge | 1.8 / 5.1 / 12.3 | 1.3 / 4.7 / 6.4 |
| Every core busy, Edge | 1.1 / 1.5 / 2.7 | 1.1 / 1.4 / 2.0 |
| CPU-bound Python thread in-process, Edge | 2.1 / 132.8 / 140.4 | 15.4 / 103.3 / 134.8 |
The hook is comfortably fast under emulation, so native ARM64 is not a fix
for anything; it was shipped for the people who notice what is left. No event in the pass reached the 200 ms
warning, none was lost, and check_health re-installed nothing. A
callback’s time is mostly in the OS calls and the other process, which is why
the two columns match although the interpreter does not: 2M rounds of pure
Python took 236 ms emulated and 79 ms native, and a new process importing the
engine, numpy and PuiKit 250 ms warm (786 cold) against 160 (307 cold). So
emulation costs CPU-bound Python about 3x, and start-up about 1.5x.
The one case that overran is not new. tests/test_win_typing_load.py, with
the keys going to its own process’s window under emulated x64: p50 0.2-0.55
ms and p95 under 1.5 ms in ordinary use, but one CPU-bound Python thread
reached a max of 360 ms, past LowLevelHooksTimeout, as the entry above
on typing latency says it can. That module was not run natively, so whether
emulation widens it is not measured; the pass’s own GIL rows (max 120-159 ms
emulated, 135-145 ms native) show no difference.
Limits: one run of each, a VM, and input from SendInput rather than a
keyboard. Only the hook, the engine and UIA ran natively here, not PuiKit’s
windows or a native bundle. The pass does not cover a window that pumps
slowly, which costs what the application costs on either architecture.
platform.machine() says ARM64 in the emulated process too (the pass prints
sysconfig.get_platform() to tell them apart). python_packages.platform_tag()
was keeping x64 and ARM64 packages together on one machine for that reason, and
now uses the interpreter’s architecture on Windows.
Native ARM64 bundles (2026-11-05, issue #318, the same VM with VS Build
Tools added for the run; build.ps1 from an x64 venv, with both ARM64- and
x64-hosted compilers). Both bundles were started as real Keyhac.exe
processes with Notepad in front, and timed from SendInput(F13) to the
remapped F14 reaching a low-level hook in the measuring process, which is x64
in both columns. 500 taps at about 30 keys/s, none lost:
| x64 emulated | ARM64 native | |
|---|---|---|
| F13 to F14, p50 / p95 / p99 / max ms | 4.81 / 6.18 / 7.73 / 30.83 | 3.10 / 5.26 / 6.29 / 11.45 |
| First launch after build, to first remap | 1.09 s | 0.6 s |
So the whole trip through the hook, engine and injection is about 1.7 ms
shorter at the median, which the callback timings above did not show because
they stop at the callback’s edges. Later launches measure the same at 0.5 s,
but the probe retried every 0.2 s, so that is no finer than its step.
tools/bundle_pass.py passes 11/11 on the ARM64 bundle. The signed
.msixbundle installs on this Arm machine as Keyhac.Prototype_..._arm64,
starts from C:\Program Files\WindowsApps, and keyhac-mcp-bridge.exe
resolves through its alias. Add-AppxPackage over SSH fails with 0x80070005
and works from a scheduled task in the desktop session. Every PE in the ARM64
bundle is ARM64 except runtime\vcruntime140_1.dll, which python.org’s
embed-arm64 itself ships as x64. Not exercised: the x64 payload on real x64
hardware. The Store accepted the bundle with 2.8.0: its public catalog lists
craftware.Keyhac_2.8.0.0_neutral_~ as an MsixBundle of x64 and arm64, though
nothing here was installed from the Store. make test-vm GUEST=qa-win
ARCH=arm64 passes 1691 tests with 105 skipped under the native ARM64 Python.
test_the_real_git_answers_mean_what_identity_expects failed there and on x64
because QA-2026-11-03 has no git, and is now host_only, as the tooling it
tests is. The x64 suite then passes whole: 1691 passed, 106 skipped.
The genuinely-interactive checks were tracked in issue #10 and are all through as of 2026-08-07, but they are a standing pass, not a burnt-down backlog: they describe what to repeat before a release, since nothing here is covered by the automated harnesses. The two that needed hardware this machine does not have — a JIS keyboard, and a Japanese input method — were passed by hand on 2026-08-07 and stay on the list for the next release rather than being struck off. What the IME entry checks inverted on 2026-08-26: the chooser no longer takes keyboard focus, so its filter field no longer composes, and that is now the thing to confirm rather than the thing to fix.
ActivateApplication’s window rotation, on both OSes (new, not yet
passed) — tests/test_activate.py pins the choice of target against fake
windows; what it cannot exercise is the ordering the real platforms report.
Open three windows of one application in different screen positions and hold
the key down through a full cycle: every window must be reached, in screen
order, with no pair swapping back and forth (the failure mode the walk over
positions exists to prevent). Then, with the application behind, one press
must bring it forward rather than advance the rotation; quit it and one press
must launch it. On macOS repeat with a localized application name, since
app= matches what the OS reports.
Maximize, restore and SnapWindow on a maximized window, on Windows
(passed 2026-10-14, Windows 11 26200, Chrome) — issue #157; the
reasoning and the macOS measurements are in
design-notes.md.
tests/test_win_window.py’s TestMaximize pins the round trips on a window
this process owns (maximize → is_maximized(); restore() → not; a
minimized maximized window is minimized only, and restore() brings it back
maximized; set_frame, with or without a size, ends the state; every verb
with nothing to do returns False), and TestSnapLive the #157 case itself.
Taking the SW_RESTORE out of set_frame fails three of them, and on
Chrome makes SnapWindow on a maximized window do nothing visible. What is
left for the eye, on Chrome, where #157 saw it fail: maximize it, run
SnapWindow("left"), and check that it lands on the left half and that
double-clicking its title bar afterwards maximizes it and a second
double-click brings it back to the left half. Then the same starting from
a window Windows snapped itself (Win+Right): before the fix the first
double-click went back to the size from before Win+Right, because a window
the OS snapped stays “arranged” (IsWindowArranged) wherever
SetWindowPos puts it; set_frame now SW_RESTOREs that state too.
SetWindowPlacement with the new normal rect also clears it without the
brief flash of the old size, but its rect is in workspace coordinates,
which are not screen coordinates once the taskbar is on the top or left.
The other two open questions answered on the way: Chrome honors
ShowWindow(SW_MAXIMIZE) (it handles its own non-client area, so it was
the likeliest to ignore one), and the state read back straight after
ShowWindow on another process’s window is the new one (maximize 7–8 ms,
minimize 5–37 ms, read back True each time). Drive a Chrome started with a
throwaway --user-data-dir, never the user’s own, and double-click the
empty tab strip — at high DPI the caption buttons reach well over 260 px
in from the right edge. is_full_screen() and enter_full_screen() stay
the base False on Windows by design.
Window geometry against Windows’ own snap (new, not yet passed) —
WinWindow.get_frame/set_frame now work in the visible frame (DWM’s
EXTENDED_FRAME_BOUNDS) instead of the window rect, so SnapWindow and
MoveWindow place a window where the OS itself would; before, every edge
landed ~7px short at 100% DPI, twice that between two tiles.
tests/test_win_window.py pins the round-trip on a window this process owns,
and cannot judge the result by eye. Snap one window left with SnapWindow
and another with Win+Left and compare the edges; tile two side by side and
look for a seam; repeat at a display scale other than 100%, and on a window
with no resize border (Settings, or another UWP app), where the compensation
must come out zero rather than wrong.
The chooser on Windows, after the non-activating rework (new, not yet
passed) — this branch changed the chooser on both OSes but was developed and
live-checked only on macOS, and Windows takes the other code path:
overlay_input has no Windows equivalent and is inert, so the window is a
plain WS_EX_NOACTIVATE + WS_POPUP one with no panel behind it. Nothing
below is covered by the harnesses, because all of it is about what the OS does
with a window that never takes focus.
tests/test_win_char_for_key.py covers the
mechanism (ToUnicodeEx) and runs on any layout; what it cannot reach is a
layout with an AltGr layer (@ and the backslash on German/Nordic) or a
dead key. If such a keyboard is available, type both; if not, skip it
honestly — the dead-key path deliberately calls ToUnicodeEx twice for the
builds that ignore TOUNICODE_NO_STATE, and only real hardware proves the
next keystroke is not left composing._PASTE_DELAY is now skipped entirely on this path, so a paste that lands
in the wrong place or not at all is this check failing.frameless is set on both OSes
because macOS needs it to hide the title bar its panel mask forces; on
Windows that means WS_POPUP, so the chooser lost the frame it had in
2.x. Confirm it still reads as a window and not as a floating rectangle.WS_EX_NOACTIVATE never did), so this is
confirming nothing regressed rather than checking a fix.pymigemo is a hard dependency now. The LP64 dictionary
patch is inert on Windows (array('L') is already 4 bytes there), so this
is confirming the engine reports itself loaded and that romaji finds
Japanese in the filter — not the patch.Keyhac.exe bundle — tools/bundle_pass.py does the mechanizable
half; run it with no Keyhac running, or the instance guard makes every check
fail for the wrong reason. 11/11 for 2.2.1, on a bundle rebuilt against the
PyPI PuiKit wheel — which exercises two paths an editable checkout never
does: the bundled fonts coming from the wheel instead of scripts/
fetch_fonts.py, and PuiKit’s LICENSE being read out of puikit-*.dist-info
instead of a checkout root. By hand alongside it (passed 2026-08-08): the
tray icon and its menu clicks, and the console’s log pane, hook checkbox and
log-level dropdown.is_stale() against a really-destroyed element — tools/uia_pass.py’s
staleness section, which owns its own window precisely because it has to
destroy it. It is not a formality: matching UIA_E_ELEMENTNOTAVAILABLE alone
was wrong, because a control destroyed underneath us answers E_UNEXPECTED
for its first ~90 ms and only then settles on the named constant — so
is_stale() said False during the one moment it is asked, and _press
blamed the operator’s selector for a dialog that had closed. A destroyed
top-level window was once only reported, as a coin flip: UIA sometimes
kept answering S_OK with its ControlType degraded Window→Pane, and
sometimes failed. It was never random — it is the window class. A
dialog (#32770) destroyed while its process lives on degrades to Pane
every time; a private-class window, or one whose process exits, fails the
read. The degrading case is what made Gone(node) time out on a dialog’s
Cancel (issue #189, fixed by PR #192, which checks the window’s own handle
with IsWindow). The pass now spawns that dialog, destroys it on its own
thread, and checks is_stale() and Gone(node) both see it go. A
note: line shows whether UIA really answered S_OK/Pane on that run — if it
ever stops doing so, the checks still pass but no longer exercise the fix.The chooser filter box with a Japanese input method selected (rewritten 2026-08-26; the previous version of this check asserted the opposite and would now fail by design) — the chooser stopped taking keyboard focus, and composition follows that focus, so the filter field cannot compose and is not meant to. Confirm instead:
ka with the IME on puts ka in the field — the hook feeds it
characters directly and the input method never sees the keys;kensaku finds an entry containing 検索, which is how Japanese is reached
now (keyhac/core/migemo.py; pymigemo is a hard dependency, so an engine
that fails to load is a release blocker, not a degradation);The reasoning behind giving composition up, and what overlay_input="keyboard"
would cost to get it back, is in design-notes.md. PuiKit’s
per-window input contexts (keyhac #20, puikit PR #90) are still what the
console relies on; they are simply no longer on the chooser’s path.
Kanji,
Henkan and Muhenkan actually match the 半角/全角, 変換 and 無変換 keys when
pressed on JIS hardware. The VKs (0x19 / 0x1C / 0x1D) are the documented ones,
but no JIS keyboard was available to confirm what the hardware really reports;
the console’s last-key display is the one-line check. Same hardware dependency
as the entry below, so pass them together. Still open after the 2026-08-23 IME
pass — that machine reports GetKeyboardType(0) == 4, so it cannot answer this.
What the pass did confirm is the other half of those names: injecting
VK_IME_ON/VK_IME_OFF (what Kana/Eisu send) drives Microsoft IME exactly
as set_ime_status() does.GetKeyboardType(0) == 7, one
line. The tables it selects are pinned against kbd106.dll independently, so
the keyboard is needed only for the detection. It still cannot be faked on the
development VM, which presents a generic HID keyboard reporting type 4 — so
this one needs the hardware present, or it needs skipping honestly rather than
assuming. 2.2.1 took the second option: nothing in this release touches
layout detection, and recording the skip is the point of the sentence above.Where 2.2.1 left it, since “nothing outstanding” is a claim that goes stale one release at a time: on macOS the tray “Edit Config” click and mouse feel were both verified live (2026-08-07). On Windows, 2.2.1 re-passed the Japanese IME, the tray icon and menu, and the console’s log pane, hook checkbox and log-level dropdown by hand (2026-08-08), and ran the bundle pass 11/11 against a bundle built from the PyPI PuiKit wheel. The one check not repeated for 2.2.1 is JIS layout detection, for want of the keyboard — skipped and recorded, not assumed.