Skip to content

fix(nix): Kanary の Caps Lock→Control を宣言的に強制する - #972

Merged
keito4 merged 1 commit into
mainfrom
fix/kanary-caps-to-control
Jul 15, 2026
Merged

keito4 merged 1 commit into
mainfrom
fix/kanary-caps-to-control

Conversation

@keito4

@keito4 keito4 commented Jul 15, 2026

Copy link
Copy Markdown
Owner

Why(背景)

system.keyboard.remapCapsLockToControl = true(nix-darwin / hidutil)を設定済みにもかかわらず、実機で Caps Lock が Control にならず Caps Lock のままになる事象が発生。

調査の結果、Kanary が原因と判明:

  • Kanary は window-move/resize・input-switching が有効なとき、物理キーボード(Apple 内蔵)を掌握し、仮想 HID キーボード(0x5ac 0x8600)経由でイベントを再送出する
  • この再送出は hidutil の UserKeyMapping ので起きるため、hidutil の Caps→Control がバイパスされる
  • Kanary 自身の設定 capsLockRemappedToControlfalse だったため、Caps がそのまま通っていた

ADR 0016 は「Caps→Ctrl は hidutil が担当し、Kanary 設定前でも効く」としていたが、実機ではこの前提が成立しない

What(変更内容)

  • script/macos/kanary-enforce-caps-control.sh: 冪等な自己修復ヘルパー
    • capsLockRemappedToControl が既に true ならサイレント no-op
    • Kanary 未起動(設定ファイル無し)・スキーマ不明時も no-op
    • false を検知した時のみ、plist をバックアップ→当該1フィールドのみ true 化→(起動中なら)Kanary 再起動
  • nix/home/kanary.nix: ヘルパーを ~/.local/bin に設置し、home-manager の activation(writeBoundary 後)で毎回再適用。nix/home/default.nix に import 追加
  • docs/adr/0016: hidutil ベースラインが Kanary にバイパスされる実態と、Caps→Control を Kanary 側で所有・強制する方針に修正
  • テスト追加: enforcement 配線を検証

How(検証)

  • darwin-rebuild build --flake ./nix#keitonoMacBook-Pro成功(home-manager activation まで生成)
  • shellcheck -xPASS
  • jest test/nix-darwin-config.test.js17 passed(新テスト含む)
  • prettier --check(md)→ PASS / nixfmt(nix)適用済み
  • 手動適用で実機の Caps→Control 動作を確認済み

Risk / Notes

  • ヘルパーは drift 検知時のみ Kanary を再起動する(通常の switch では no-op のため無害)
  • 管理対象は Kanary 設定のうち capsLockRemappedToControl の1フィールドのみ(voice 等の他設定は非改変)
  • 別件(本 PR 対象外): 今回の switch 失敗時に、config リポジトリの .git/configcore.bare=true に破損、Mac のホスト名が a に変わっていた環境ドリフトも確認・修復済み。ホスト名を nix で宣言管理する hardening は必要なら別PRで対応可能

Summary by CodeRabbit

  • New Features

    • Added automatic enforcement of Kanary’s Caps Lock → Control remapping during Home Manager activation.
    • Added safe handling for missing, unchanged, or inactive Kanary settings.
  • Documentation

    • Clarified how Kanary controls keyboard remapping and how the setting is maintained.
  • Tests

    • Added coverage verifying the Kanary remapping configuration and enforcement setup.

@cursor

cursor Bot commented Jul 15, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@keito4, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ca77b2ef-3479-43b5-88f6-6bfa1a5baad6

📥 Commits

Reviewing files that changed from the base of the PR and between d279893 and 1f7a6fe.

📒 Files selected for processing (5)
  • docs/adr/0016-use-kanary-for-keyboard-remapping.md
  • nix/home/default.nix
  • nix/home/kanary.nix
  • script/macos/kanary-enforce-caps-control.sh
  • test/nix-darwin-config.test.js
📝 Walkthrough

Walkthrough

Adds a Home Manager module and macOS helper that enforce Kanary’s Caps Lock-to-Control setting during activation, update Kanary’s settings safely, restart Kanary when needed, document remapping ownership, and test the configuration wiring.

Changes

Kanary Caps Lock control

Layer / File(s) Summary
Enforcement behavior and remapping contract
script/macos/kanary-enforce-caps-control.sh, docs/adr/0016-use-kanary-for-keyboard-remapping.md
The helper reads Kanary’s capsLockRemappedToControl setting, updates it when false, backs up the plist, restarts Kanary when required, and documents Kanary’s ownership of remapped keyboard events.
Home Manager integration and validation
nix/home/default.nix, nix/home/kanary.nix, test/nix-darwin-config.test.js
The Kanary module is imported, the executable helper and activation step are installed, and tests verify the integration and referenced setting names.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • keito4/config#893: Earlier Kanary migration changes involving Home/host imports and Karabiner removal.
  • keito4/config#897: Related Kanary ADR and configuration assertion updates.

Suggested reviewers: github-actions[bot]

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: declaratively enforcing Kanary Caps Lock→Control remapping in nix.
Description check ✅ Passed The description covers the why, what, and validation well, but it does not follow the template’s Summary, Checklist, or Related sections exactly.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/kanary-caps-to-control

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude

claude Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Claude finished @keito4's task in 0s —— View job


I'll analyze this and get back to you.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@script/macos/kanary-enforce-caps-control.sh`:
- Line 82: Replace the `pgrep -x Kanary && pkill -9 -x Kanary || true` construct
with an explicit if statement in the Kanary termination logic, so `pkill` runs
only when `pgrep` finds the process and the fallback does not execute merely
because `pkill` fails.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 73bbd1dc-e97a-4fba-85b2-f10dafa9bd94

📥 Commits

Reviewing files that changed from the base of the PR and between 2029feb and d279893.

📒 Files selected for processing (5)
  • docs/adr/0016-use-kanary-for-keyboard-remapping.md
  • nix/home/default.nix
  • nix/home/kanary.nix
  • script/macos/kanary-enforce-caps-control.sh
  • test/nix-darwin-config.test.js

Comment thread script/macos/kanary-enforce-caps-control.sh Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d2798934a4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread nix/home/kanary.nix
Comment on lines +22 to +23
home.activation.enforceKanaryCapsControl = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
$DRY_RUN_CMD "${config.home.homeDirectory}/.local/bin/kanary-enforce-caps-control" || true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Run the Kanary hook after home-file linking

On the first darwin-rebuild switch that includes this module, the target in ~/.local/bin has not necessarily been created yet: Home Manager links home.file entries in its linkGeneration activation step, which is also only ordered after writeBoundary, so this new step has no dependency on the link being present. Because the command's failure is swallowed with || true, the initial activation can silently leave capsLockRemappedToControl unchanged until a later switch; order this after linkGeneration or invoke the store path directly.

Useful? React with 👍 / 👎.

Comment on lines +35 to +37
plutil -extract app_settings raw -o - "$PLIST" 2>/dev/null \
| base64 -D 2>/dev/null \
| python3 -c 'import sys, json

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve macOS utilities instead of activation PATH entries

When this helper is invoked from Home Manager activation, this repo's home.stateVersion = "24.11" means activation starts with a restricted PATH containing Nix tools, not /usr/bin. In that context plutil/python3/later defaults may not be found, and base64 resolves to GNU coreutils, whose help lists decoding as -d, --decode rather than macOS -D; for any activation where the Kanary setting is false, the script will skip or fail before writing while the activation masks the failure. Use absolute /usr/bin/... paths or decode/update the plist entirely via a known Nix/Python dependency.

Useful? React with 👍 / 👎.

Kanary intercepts the physical keyboard and re-emits events through a
virtual HID device when its window/input features are enabled, which
bypasses the global hidutil mapping from
system.keyboard.remapCapsLockToControl. Caps Lock therefore reverts to
Caps Lock unless Kanary's own capsLockRemappedToControl is true.

- Add script/macos/kanary-enforce-caps-control.sh: idempotent helper that
  flips only that one field to true and restarts Kanary on drift, and is a
  silent no-op once correct.
- Add nix/home/kanary.nix: install the helper and re-assert on every
  home-manager activation. Wire it into nix/home/default.nix.
- Correct ADR 0016 to reflect that the hidutil baseline is bypassed by
  Kanary and that Caps→Control is owned by Kanary's setting.
- Add a test covering the enforcement wiring.
@keito4
keito4 force-pushed the fix/kanary-caps-to-control branch from d279893 to 1f7a6fe Compare July 15, 2026 01:40
@keito4
keito4 merged commit b0d7755 into main Jul 15, 2026
17 checks passed
@keito4
keito4 deleted the fix/kanary-caps-to-control branch July 15, 2026 06:11
@github-actions

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 1.123.3 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released リリース済み

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant