Skip to content

Fix useInput crash on unmapped keyName codes#902

Merged
sindresorhus merged 2 commits into
vadimdemedes:masterfrom
costajohnt:fix/use-input-undefined-keyname
Mar 21, 2026
Merged

Fix useInput crash on unmapped keyName codes#902
sindresorhus merged 2 commits into
vadimdemedes:masterfrom
costajohnt:fix/use-input-undefined-keyname

Conversation

@costajohnt

Copy link
Copy Markdown
Contributor

Summary

  • Fix TypeError: Cannot read properties of undefined (reading 'startsWith') crash in useInput when the terminal sends escape sequences with Ctrl modifiers whose key codes aren't in the keyName map (e.g. Ctrl+F1 via ESC[1;5P)
  • Root cause: keyName[code]! non-null assertion in parse-keypress.ts returned undefined for unmapped codes, which propagated to use-input.ts and crashed on .startsWith()
  • Add missing vt220-style F1–F4 entries ([P][S]) to the keyName map so these keys resolve correctly

Fixes #901

Changes

src/parse-keypress.ts:

  • Replace keyName[code]! with keyName[code] ?? '' — removes unsafe non-null assertion
  • Add [Pf1, [Qf2, [Rf3, [Sf4 to keyName map

src/hooks/use-input.ts:

  • Add defensive ?? '' guard on keypress.name in the ctrl branch

Tests:

  • New test/parse-keypress.ts unit tests verifying key identity and empty-string fallback
  • New integration tests for Ctrl+F1 and unmapped ctrl sequences

Test plan

  • npx tsc --noEmit passes
  • All 116 related tests pass (hooks-use-input, hooks-use-input-navigation, hooks-use-input-kitty, input-parser, parse-keypress)
  • Manual repro confirms crash without fix, no crash with fix
  • Verified against all 6 crash-triggering sequences from the issue (Ctrl+F1–F4, focus-in, unmapped Ctrl+G)

parseKeypress used a non-null assertion (keyName[code]!) that returned
undefined for escape sequences not in the keyName map (e.g. Ctrl+F1
sending ESC[1;5P). This undefined propagated to use-input.ts where
.startsWith() was called on it, causing a TypeError crash.

- Replace keyName[code]! with keyName[code] ?? '' to handle unmapped codes
- Add defensive ?? '' guard in use-input.ts ctrl branch
- Add missing vt220-style F1-F4 entries ([P]-[S]) to keyName map
- Add unit tests for parseKeypress and integration tests for the fix

Fixes vadimdemedes#901
- Use Unicode escapes (\u001B) instead of hex escapes (\x1b)
- Capitalize comments to satisfy capitalized-comments rule
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.

bug: useInput crashes with TypeError when keyName lookup misses — Cannot read properties of undefined (reading 'startsWith') on VSCode v1.111.0

2 participants