Skip to content

fix(macos): survive non-string AX titles and stop leaking AXObserver - #145

Merged
ErikBjare merged 1 commit into
ActivityWatch:masterfrom
TimeToBuildBob:fix/macos-ax-title-crash
Sep 15, 2026
Merged

ErikBjare merged 1 commit into
ActivityWatch:masterfrom
TimeToBuildBob:fix/macos-ax-title-crash

Conversation

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

Summary

macOS window tracking dies in two related ways after a few days:

  1. Crash (macOS: native helper crashes when NSHTTPURLResponse is bridged as a window-title string #144). windowTitleChanged bridged kAXTitleAttribute with as? String. That path calls -[obj length] without a class check, so a non-NSString (here NSHTTPURLResponse) aborts the helper with NSInvalidArgumentException.
  2. Leak ([macOS] aw-watcher-window-macos leaks AXObserver/Mach ports, causing high wired memory #139). focusedAppChanged removed the run-loop source and then let AXObserverCreate overwrite the previous observer pointer without CFRelease. The old Mach receive port kept filling to qlimit (1024). Independently, focusedWindowChanged unregistered kAXFocusedWindowChangedNotification from the old window even though it had registered kAXTitleChangedNotification.
  3. Silent stop. The Python wrapper ignored the helper's wait status, so a SIGABRT still looked like a clean exit to aw-tauri and window tracking stayed off.

Changes

  • Read AX strings/elements via CF type ID (axString / axElement) instead of Swift's NSString bridge.
  • Tear down the previous observer: unregister title + focused-window notifications, drop the run-loop source, nil the refs, then create a new observer into a fresh out-pointer.
  • Map helper signal deaths (-6 → 134) to a non-zero wrapper exit so the module manager restarts the watcher.

Observer teardown follows the patch Gassandrid measured on #139 (200/2000 app-switch iterations, no port growth). I cannot compile the Swift helper on this Linux host; Python tests cover the exit-status path.

Related

Test plan

  • poetry run python -m pytest tests/test_main.py (19 passed)
  • poetry run mypy aw_watcher_window/ --ignore-missing-imports
  • On macOS: make build-swift
  • Switch apps rapidly and confirm aw-watcher-window-macos Mach port count stays bounded (sudo lsmp / sudo zprint)
  • Confirm a helper abort now makes aw-watcher-window exit non-zero so aw-tauri restarts it

Accessibility can return non-NSString values for kAXTitleAttribute.
Bridging those with `as? String` calls `-[obj length]` and aborts the
helper (NSHTTPURLResponse in ActivityWatch#144). Read titles via CF type checks.

Also tear down the previous AXObserver properly: unregister the title
and focused-window notifications, drop the run-loop source, and nil the
observer before AXObserverCreate. Overwriting the CF out-pointer leaked
Mach receive ports and wired memory (ActivityWatch#139).

If the helper still dies, propagate its signal/exit status so aw-tauri
restarts window tracking instead of treating the crash as a clean
shutdown.

Git-Session-Id: 03164cc9-6bb0-5435-925f-f425e310dded
@ErikBjare

Copy link
Copy Markdown
Member

@greptileai review

@ErikBjare

Copy link
Copy Markdown
Member

@TimeToBuildBob review

@TimeToBuildBob TimeToBuildBob left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against #144, #139 (Gassandrid's measured teardown), and aw-tauri's module manager. I authored this PR; this is the adversarial pass.

Verdict: land it. No blocking issues. GitHub will not let me approve my own PR.

Crash path (#144)

as? String on an AX value really does go through String._unconditionallyBridgeFromObjectiveC → -[obj length] with no class check. NSHTTPURLResponse is exactly that trap. axString / axElement via CFGetTypeID is the right fix, and every AX title/role/focused-window read on this path is converted.

The leftover urlRef as? NSURL is a different bridge (class-checked) and is the URL success path; axString is only the CFString fallback.

Leak path (#139)

tearDownObserver matches the patch Gassandrid measured at 200 and 2,000 app-switch iterations (no Mach-port growth):

  1. Unregister kAXTitleChangedNotification on oldWindow
  2. Unregister kAXFocusedWindowChangedNotification on observedApp
  3. Drop the run-loop source
  4. Nil the refs so Swift ARC releases the AXObserver (the Mach-port owner)
  5. Create into a fresh out-pointer, not &observer

Two extras vs that patch, both correct: deinit also tears down, and pollActiveWindow no longer force-unwraps a nil observer. RunLoop.current for both add and remove is consistent — mixing main/current (as the #139 sketch did) would leak if those ever diverged.

Exit status

swift_helper_exit_status(-6) == 134 is the mapping Popen.wait() uses for SIGABRT. aw-tauri restarts only when !output.status.success() (manager.rs); exit 0 was the silent-off. stop_module sets modules_pending_shutdown before SIGTERM, so mapping helper SIGTERM → 143 will not restart during quit. aw-qt already treats any death-while-started as unexpected (dialog, no auto-restart) — this change is for the tauri path.

Tests cover the mapping and the swift-strategy SystemExit(134) path.

CI

macos-latest already compiled this:

swiftc -target arm64-apple-macosx12.0 aw_watcher_window/macos.swift

Succeeded. The two warnings (optional interpolation in the Chrome/Safari title-diff logs) are pre-existing. The unchecked make build-swift box in the PR body is stale.

Out of scope

  • #141 also rewrites observer lifecycle and will conflict. Land this first: it actually type-checks AX strings and unregisters the app-level focused-window notification; #141 does neither, and still has windowTitle as? String.
  • Chrome/Safari ScriptingBridge failure still returns without a heartbeat. That's #141, not this PR.
  • Remaining live check I cannot do here: Mach-port count under rapid app switching (sudo lsmp). Gassandrid already ran that harness against this teardown; CI compiled the helper but did not rerun it.

No code changes requested.

@ErikBjare
ErikBjare merged commit a82b6d1 into ActivityWatch:master Sep 15, 2026
6 checks passed
TimeToBuildBob added a commit to TimeToBuildBob/aw-watcher-window that referenced this pull request Oct 2, 2026
…ctivityWatch#145)

Accessibility can return non-NSString values for kAXTitleAttribute.
Bridging those with `as? String` calls `-[obj length]` and aborts the
helper (NSHTTPURLResponse in ActivityWatch#144). Read titles via CF type checks.

Also tear down the previous AXObserver properly: unregister the title
and focused-window notifications, drop the run-loop source, and nil the
observer before AXObserverCreate. Overwriting the CF out-pointer leaked
Mach receive ports and wired memory (ActivityWatch#139).

If the helper still dies, propagate its signal/exit status so aw-tauri
restarts window tracking instead of treating the crash as a clean
shutdown.

Git-Session-Id: 03164cc9-6bb0-5435-925f-f425e310dded
TimeToBuildBob added a commit to TimeToBuildBob/aw-watcher-window that referenced this pull request Oct 6, 2026
Rebase of ActivityWatch#141 (hawai-i) onto current
master after ActivityWatch#145.

Keep PID-based foreground reconciliation and emit a heartbeat when
Chrome/Safari ScriptingBridge fails, so merging does not extend the
previous application across the real browser interval.

Preserve ActivityWatch#145 AX safety (axString/axElement) and observer teardown
(unregister focused-window notification, track observedApp).

Chrome context-failure fallback keeps app identity for tracking but
drops title and URL: ScriptingBridge is the only incognito detector
(Greptile P1 on ActivityWatch#141). Swift state tests now compile with the macOS
12 deployment target (Greptile P2).

Co-Authored-By: hawai-i <32040032+hawai-i@users.noreply.github.com>
Git-Session-Id: 9615c06b-2a11-592d-b1ad-299a3433e323
TimeToBuildBob added a commit to TimeToBuildBob/aw-watcher-window that referenced this pull request Oct 14, 2026
Rebase of ActivityWatch#141 (hawai-i) onto current
master after ActivityWatch#145.

Keep PID-based foreground reconciliation and emit a heartbeat when
Chrome/Safari ScriptingBridge fails, so merging does not extend the
previous application across the real browser interval.

Preserve ActivityWatch#145 AX safety (axString/axElement) and observer teardown
(unregister focused-window notification, track observedApp).

Chrome context-failure fallback keeps app identity for tracking but
drops title and URL: ScriptingBridge is the only incognito detector
(Greptile P1 on ActivityWatch#141). Swift state tests now compile with the macOS
12 deployment target (Greptile P2).

Co-Authored-By: hawai-i <32040032+hawai-i@users.noreply.github.com>
Git-Session-Id: 9615c06b-2a11-592d-b1ad-299a3433e323
TimeToBuildBob added a commit to TimeToBuildBob/aw-watcher-window that referenced this pull request Nov 4, 2026
Rebase of ActivityWatch#141 (hawai-i) onto current
master after ActivityWatch#145.

Keep PID-based foreground reconciliation and emit a heartbeat when
Chrome/Safari ScriptingBridge fails, so merging does not extend the
previous application across the real browser interval.

Preserve ActivityWatch#145 AX safety (axString/axElement) and observer teardown
(unregister focused-window notification, track observedApp).

Chrome context-failure fallback keeps app identity for tracking but
drops title and URL: ScriptingBridge is the only incognito detector
(Greptile P1 on ActivityWatch#141). Swift state tests now compile with the macOS
12 deployment target (Greptile P2).

Co-Authored-By: hawai-i <32040032+hawai-i@users.noreply.github.com>
Git-Session-Id: 9615c06b-2a11-592d-b1ad-299a3433e323
ErikBjare pushed a commit that referenced this pull request Nov 4, 2026
* fix(macos): rebase foreground reconciliation onto master

Rebase of #141 (hawai-i) onto current
master after #145.

Keep PID-based foreground reconciliation and emit a heartbeat when
Chrome/Safari ScriptingBridge fails, so merging does not extend the
previous application across the real browser interval.

Preserve #145 AX safety (axString/axElement) and observer teardown
(unregister focused-window notification, track observedApp).

Chrome context-failure fallback keeps app identity for tracking but
drops title and URL: ScriptingBridge is the only incognito detector
(Greptile P1 on #141). Swift state tests now compile with the macOS
12 deployment target (Greptile P2).

Co-Authored-By: hawai-i <32040032+hawai-i@users.noreply.github.com>
Git-Session-Id: 9615c06b-2a11-592d-b1ad-299a3433e323

* fix(macos): restore @main entry so two-file swiftc compiles

Adding macos_state.swift made macos.swift a non-script compilation unit.
Top-level assignments (formatter options, encoder strategy, start()) are
illegal outside main.swift. Restore the #141 closure inits and @main
wrapper that the rebase dropped.

Git-Session-Id: ca3f0209-55b1-58ce-8820-82fb6f5bc8e0

* fix(macos): drop stale same-window title callbacks and Safari AX titles

PID-only AX guards accepted queued title-change events from a previous
window of the same app. Bind title callbacks to the focused window.

Safari ScriptingBridge failure kept the AX window title, unlike Chrome.
Use the same keep-app / drop-title-URL fallback so private pages cannot
leak via accessibility when context lookup fails.

Git-Session-Id: 9a7625ed-1cac-5d98-b0d9-013b84aae02d

* fix(macos): release unused AXObserver when notification add fails

rebuildObserver created an AXObserver then returned on
AXObserverAddNotification failure without adopting it, leaking the Mach
port. Adopt and tear down through the #139 path. Bind foreground
identity in the caller so a failed install still emits a heartbeat.

Git-Session-Id: 28375f79-1abe-5518-8f8c-75fcc067315a

* fix(macos): drop unused AXObserver via ARC and isolate swift tests

The add-failure path never installed the observer in the run loop, so
tearDownObserver's CFRunLoopRemoveSource was a no-op. Nil the managed
reference instead; CFRelease would double-free a Swift-ARC CF type.

Write the Swift state-test binary into a mktemp directory so make test
does not execute a predictable path in /tmp.

Git-Session-Id: 28375f79-1abe-5518-8f8c-75fcc067315a

* fix(macos): retry title-change observer after transient AX add failure

If AXObserverAddNotification for kAXTitleChangedNotification fails once,
keep the focused window but leave registration retryable so the next poll
can install it. Poll heartbeats already carry the current AX title; this
restores live title-change callbacks after a transient add failure.

Git-Session-Id: 2b8b1429-6ecf-575e-b812-491b60c68d9e

* fix(macos): preserve app exclusion in reconciled heartbeat path

Git-Session-Id: 857984da-6219-579c-b1f4-44a9cc88fa80

---------

Co-authored-by: hawai-i <32040032+hawai-i@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants