Skip to content

Add SmartLayout macOS app: keyboard layout switcher with AI corrections - #1

Open
doufort wants to merge 11 commits into
mainfrom
claude/app-tests-skills-hooks-ld2rwy
Open

doufort wants to merge 11 commits into
mainfrom
claude/app-tests-skills-hooks-ld2rwy

Conversation

@doufort

@doufort doufort commented Oct 10, 2026

Copy link
Copy Markdown
Owner

Summary

This PR introduces SmartLayout, a complete macOS menu bar application that automatically corrects keyboard layout mistakes and typos while you type. The app detects when text is typed in the wrong keyboard layout (e.g., ghbdtn instead of привет), fixes spelling errors, and optionally provides AI-powered text suggestions.

Key Changes

Core Application Structure

  • AppDelegate.swift: Main application entry point managing keyboard monitoring, AI controller, and system integration
  • main.swift: Minimal entry point setting up NSApplication with menu bar-only mode
  • KeyboardMonitor.swift: Global keyboard event interception using Carbon APIs to capture typed characters and apply corrections in real-time
  • CorrectionEngine.swift: Logic for detecting layout mismatches and spelling errors using macOS spell checker

Layout Conversion & Correction

  • LayoutMap.swift: Bidirectional EN QWERTY ↔ Russian ЙЦУКЕН keyboard layout mapping with character conversion tables
  • TextAccess.swift: Accessibility API integration to read/modify text in other applications
  • InputSource.swift: Keyboard layout detection and switching via Text Input Sources

AI Integration

  • AIController.swift: Manages AI-powered text checking with pause-based suggestions and hotkey-triggered corrections
  • AIClient.swift: OpenAI-compatible API client supporting multiple providers (OpenAI, Yandex Cloud, local Ollama)
  • ConversationMemory.swift: Maintains conversation context window for better AI suggestions
  • StyleProfile.swift: Learns and applies user's writing style to AI suggestions
  • HumanStyle.swift: Enforces natural language rules to prevent AI-generated text appearance

Learning & Personalization

  • LearningStore.swift: Persistent local storage of learned words, accepted corrections, and user preferences
  • WordStore.swift: Manages dictionaries (slang, typos, user words) and learned exceptions
  • Settings.swift: User preferences for auto-correction, AI settings, and behavior tuning

UI & System Integration

  • SettingsWindow.swift: Preferences window for AI provider configuration and feature toggles
  • SuggestionPanel.swift: Floating suggestion window showing corrections without stealing focus
  • HotKeys.swift: Global hotkey registration for manual correction triggers
  • Keychain.swift: Secure API key storage in macOS Keychain
  • LoginItem.swift: Auto-launch configuration via launchd
  • AppExclusions.swift: Whitelist/blacklist for applications (terminals, password managers excluded by default)

Dictionaries & Resources

  • slang_ru.txt / slang_en.txt: 350+ slang terms and abbreviations to skip correction
  • typos_ru.txt / typos_en.txt: Common misspellings with corrections
  • style_profile.json: Default writing style profile

Build & Testing

  • build_app.sh: Build script supporting universal binaries, code signing, and DMG packaging
  • Package.swift: Swift Package Manager configuration for macOS 13+
  • Comprehensive test suite:
    • CoreTests.swift: Layout conversion and text utilities
    • AuditFixesTests.swift: Security and exclusion logic
    • RegressionTests.swift: Learning store persistence
  • Python validation tools:
    • check_dicts.py: Dictionary format and consistency validation
    • bundle.py: Binary inspection without macOS tools
    • swift_source.py: Extract constants from Swift for cross-language testing
    • layout_map.py: Python model of keyboard layout conversion
    • pytests/: Comprehensive test suite for dictionaries, sources, and built artifacts

Documentation & CI

  • README.md: User-facing documentation with feature overview
  • CLAUDE.md: Developer guide for Claude Code integration
  • docs/AUDIT.md: Security audit results and known issues
  • .github/workflows/ci.yml: GitHub Actions CI pipeline
  • .claude/: Claude Code integration with skills and validation hooks

Notable Implementation Details

  • Real-time keyboard interception: Uses Carbon APIs (CFMachPort) to intercept keyboard events globally

https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3

claude added 11 commits October 10, 2026 13:54
Swift package, resources, build script and AI load test as provided
by the author (SmartLayout_v_1.zip).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
- KeyboardMonitor: Backspace-undo no longer armed after Enter/Tab,
  which erased text in the next message or another field.
- CorrectionEngine: domains and abbreviations (google.com, mail.ru,
  e.g.) are no longer converted to the Russian layout.
- SuggestionPanel: only Esc/Cancel count as rejecting a suggestion;
  typing on or a timeout no longer teaches the AI to never fix a word.
- LearningStore: words merely typed 3 times go to typedWords and are
  not sent to the AI as protected; tolerant decoding keeps learned data
  across schema changes; pending changes are flushed on quit.
- WordStore/LearningStore take directory, defaults and resources so
  tests no longer wipe the user's real learning.json.
- Clipboard: snapshot/restore all pasteboard items and types; leave the
  pasteboard alone when nothing was copied or the user copied meanwhile.
- AIClient: truncated JSON replies are rejected instead of being offered
  (and pasted) as the corrected text.
- build_app.sh: VERSION (default 1.0) and UNIVERSAL=1.
- Regression XCTests for all of the above; tests run in temp dirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
- pytest suite (runs on Linux): dictionaries, Swift sources and
  build_app.sh, and the released dist/SmartLayout-1.0.dmg (archs,
  signature, Info.plist, LaunchAgent, resources, strings vs sources).
  Known open defects are strict xfails referencing docs/AUDIT.md.
- tools/: dictionary validator, Mach-O/.dmg inspector, readers for
  constants in the Swift sources.
- CI: pytest on Linux; swift build, swift test and build_app.sh on macOS.
- .claude: SessionStart setup, PreToolUse guard for release artifacts,
  PostToolUse validation (dictionaries, build script, swiftc -parse,
  pytest); project skills for dictionaries, Swift fixes, release audit.
- docs/AUDIT.md: fixed and open issues, comparison with RuSwitcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
macOS file systems are case-insensitive, so tests/ (pytest) and Tests/
(XCTest) collapsed into one directory and CI could not find
tests/test_bundle.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
- AppExclusions: terminals, code editors and password managers are left
  alone by default (password managers cannot be re-enabled); menu toggle
  "Не работать в «…»"; ⏸ in the menu bar title.
- Password fields: KeyboardMonitor skips Secure Input and AXSecureTextField
  (no fixes, no learning, nothing in typedText); TextAccess.read and the
  AI hotkeys never read secure fields; 🔒 in the title.
- LayoutMap: key table built from the enabled layouts via UCKeyTranslate
  (works with Apple "Russian", not only "Russian – PC"); built-in table
  stays as fallback.
- Privacy: AI auto-check and window text are off for new installs and
  need explicit consent; existing 1.0 users keep their behaviour; window
  text is a separate toggle; personal style profile can live in
  Application Support; API key never sent over http:// to the internet;
  LAN hosts count as local.
- CorrectionEngine: warm-up at launch; a slow NSSpellChecker answer
  pauses early layout detection for a minute instead of stalling the tap.
- Hotkeys: ⌥⇧F/⌥⇧I or ⌃⌥F/⌃⌥I, chosen in settings.
- build_app.sh: universal when Xcode is present, icon, hardened runtime,
  SIGN_ID for Developer ID, `dmg` target with optional notarization,
  version 1.1. CI builds the DMG and uploads it.
- Tests: XCTest for all of the above; bundle tests expect the 1.0 defects
  only in the 1.0 release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
- KeyboardLayouts: the key left of 1 is code 10 on ISO keyboards and 50
  on ANSI; pick the order by keyboard type so ё/Ё come from one key,
  and keep only Cyrillic letters in ruToEn (Russian-PC has a Latin Ë).
- Settings: aiAutoCheck/aiReadWindow are no longer registered defaults
  (the registration domain is process-wide and hid unset values from
  the 1.0 migration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
The new AIConfig.sendsKeyInsecurely check puts "http://" into the
binary; only strings with a host are endpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
Typing
- Lexicon: frequency word lists (FrequencyWords, CC BY-SA 4.0, see
  Resources/WORDLISTS_LICENSE.txt, tools/build_wordlists.py) answer
  "is this a word / a word start" instantly.
- CorrectionEngine.evaluateCached never calls NSSpellChecker; unknown
  words are checked with the asynchronous requestChecking API and the
  word is fixed right after (KeyboardMonitor.lateFix, only if nothing
  was typed since). Enter/Tab still check synchronously unless slow.
- Early layout detection uses the lexicon, from the 4th letter.
- Password-field check is cached until focus changes.
- Dropped .latencyCritical from the App Nap activity.
- HumanStyle: regex compiled once, literal substring search.

AI
- Typing cancels an in-flight auto-check request.
- Review: the corrected text is shown at once; a rejected alternative
  is rewritten in the background and added when it arrives.
- Cache of recent answers (review/fix, 10 min, 64 entries).
- Stable system message (prompt + style profile) for provider prompt
  caching; changing parts go to the user message.
- Connection to the provider is warmed up while you type.

Tests: Lexicon, cached/background evaluation (incl. parity with the
sync checker), early detection, URLProtocol-stubbed AI client (one
request for review, retry for improve, cancellation), prompt order,
answer cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
Lexicon takes ~0.5 s to build (CI measure), so it is loaded off the main
thread at launch and handed to CorrectionEngine via use(_:); until then
the engine uses the spell checker as before. Prefixes are cut by
Unicode scalars. The background alternative rewrite captures the
app-lifetime AIController directly (no Swift 6 'captured var' warning).
Audit doc gets the CI before/after numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UabTyFuT4Mg6wqSGGNyi3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants