hex/ios/docs/typing-logs.md
Ryan Vogel 9d26cbdb87
iOS: fix six TestFlight tester issues (audio error, leaked error text, Live Activity, haptics, capitals, push to talk) (#2035)
* iOS: retry '!int' audio activation mixable and show audio errors as sentences

TestFlight testers saw "The operation couldn't be completed. (OSStatus error
560557684.)" in the keyboard strip and the app's setup card. 560557684 is
'!int' (AVAudioSession cannotInterruptOthers): a non-mixable session (the
Bluetooth-microphone .record category) going active from the background while
another app plays or records.

- AudioBackend: when setActive(true) fails with '!int', set .playAndRecord
  with .mixWithOthers (keeping HFP when Bluetooth is allowed) and activate
  once more, so the warm keepalive and captures start alongside the other
  app's audio instead of failing.
- New UserFacingError (HEXShared, app and keyboard): AVAudioSession codes map
  to short sentences ("Another app is using audio. Try again."); other
  microphone errors get "Hex couldn't start the microphone. Try again.";
  transcription and model errors keep their description only when it reads
  as a sentence, never Foundation's "couldn't be completed (… error N)" or a
  Swift type name.
- DictationController: every error it shows (phase .failed and the
  keyboard's message) goes through UserFacingError instead of
  localizedDescription.

Verified: xcodebuild test on the iPhone 18 Pro simulator, 179 tests pass,
including new tests for the code-to-sentence mapping and for a warm session
whose keepalive throws '!int' reaching the app and keyboard snapshot as
"Another app is using audio. Try again.". The background '!int' retry itself
needs a physical iPhone (music playing, Bluetooth mic allowed, warm session).

* iOS: end empty dictations quietly and keep error text human in the keyboard

Tapping Done (or ✕) in the keyboard's dictation screen without speaking
showed "Transcription failed: HEXKeyboard.(unknown context at $1…)": the
in-keyboard path printed the error's domain (a private Swift type name),
code and description for Apple Speech's "no words" result.

- New EmptyCapture rule (HEXShared): a capture under 0.3 s (or none at all)
  is a tap, and an engine's no-speech error or a cancellation means nothing
  was said; both end quietly. Engines say so through NoSpeechError
  (Parakeet's and Apple Speech's emptyTranscript, the keyboard's
  KeyboardSpeech.Failure.empty).
- KeyboardLocalDictation: Done before the microphone came up, or a capture
  too short to hold a word, returns to idle without transcribing (and a late
  "started" from WebKit stops the capture instead of opening a file);
  no-speech ends quietly; a transcription error from a cancelled or
  superseded job is dropped; every other failure shows a sentence from
  UserFacingError or the keyboard's own copy, while the probe log keeps the
  domain and code. KeyboardSpeech.Failure's descriptions are now sentences.
- DictationController (warm session and app): an engine's no-speech error
  returns to Ready with no message instead of failing.

Verified: xcodebuild test on the iPhone 18 Pro simulator after rebasing onto
origin/dev (bba07c64), 210 tests pass (1 skipped as before), including new
tests for the empty-capture rule and for a warm keyboard dictation whose
transcriber hears nothing (Ready, no message) next to one that fails (a
sentence). The in-keyboard WebKit capture path needs a physical iPhone.

* iOS: start Live Activities only for system dictations and end them reliably

Testers saw Hex's activity (dots + ✓, expanded "Copied") stay in the
Dynamic Island, even with Keep mic warm Off. The ✓/Copied look is the
widget's stale rendering of an activity nobody ended: every recording
(keyboard warm dictations and in-app ones included) requested an activity,
and the end ran in a detached task that a suspending app (microphone just
released) could skip, so it went stale and stayed for hours.

- DictationController requests an activity only for dictations that copy
  (Action Button, Control Center, Siri/Shortcuts); the keyboard and the app
  show their own recording UI. Removed: the activity for keyboard and in-app
  dictations.
- LiveActivityCoordinator: ending (cancel, failure, short capture, warm
  session cancel) ends every Hex activity there is at that moment with
  .immediate; Copied still lingers 2 s via .after. Ends run under a UIKit
  background task, and a dictation that is transcribing keeps one until its
  activity ends. A current activity the system already ended is replaced
  rather than updated.
- Stale activities end at launch (DictationController.shared init), when Hex
  becomes active, and when the warm session ends or Keep mic warm is set to
  Off, unless a dictation is recording or transcribing.
- README: when Live Activities show and end.

Verified: xcodebuild test on the iPhone 18 Pro simulator, 210 tests pass
(1 skipped as before). A temporary, uncommitted test on the simulator showed
no activity for a warm keyboard dictation, one for a copy dictation that
ended after Copied, one ended at once on cancel, and an orphan activity
ended by Keep mic warm › Off. The Dynamic Island itself, and background
suspension timing, need a physical iPhone.

* iOS: give the dictation bar's keys the full keyboard's light haptic

The full keyboard taps under the finger (Experiments › Haptics, with Full
Access); the dictation bar's keys had no haptic at all.

- KeyboardViewModel gains onKeyFeedback; every control on the dictation bar
  calls it: Hex mark, Dictate / Set up, ✕ and Done, Swipe and its return-app
  chips, the style and language triggers and chips, the tray's close button,
  space, return, and delete (each repeat, as the full keyboard's delete).
- KeyboardViewController plays a light impact at the full keyboard's 0.65
  intensity, under the same rule the full keyboard now shares
  (allowsKeyHaptics: Full Access and FullKeyboardSettings().haptics).
- Experiments: the Haptics switch moves out of the Full keyboard group so it
  shows whether or not the full keyboard is on; same key
  (settings.keyboardHaptics), subtitle now says it covers Hex's keys.

Verified: xcodebuild test on the iPhone 18 Pro simulator, 210 tests pass (1
skipped as before); Experiments rendered with --snap-state experiments shows
Haptics after Keyboard layout, outside the Full keyboard rows. The haptic
itself (and its Full Access gate) needs a physical iPhone; the simulator has
no Taptic Engine.

* iOS: lowercase a dictation that continues a sentence

A tester typed a few words, dictated, and the dictation started with a
capital as if it began a sentence: speech engines capitalize every result.

- TranscriptFormatter.startsSentence(after:): the text before the cursor ends
  a sentence when it is empty or only spaces, or its last mark is . ! ? … 。
  or a line break (closing quotes and brackets after them count too).
- TranscriptFormatter.continuingSentence: mid-sentence, the first letter goes
  lowercase unless the first word is "I" or an I' contraction, all capitals
  (2+ letters), has capitals inside (McDonald's), or its lowercase form isn't
  in the dictation language's dictionary (likely a name).
- insertionText takes that dictionary (isWord; nil keeps the case), never
  adds a second space after one already there (spaces at the start of the
  dictation are dropped), and adds none after an opening ( [ { " “ ‘ « ¿ ¡.
- KeyboardViewController (the one place both keyboards insert a dictation)
  passes a UITextChecker for the dictation language (Apple Speech's last
  resolved language, else Settings' or Automatic's, else the first
  preferred language), mapped by KeyboardLanguage.spellCheckLanguage(
  forDictation:available:). German and Luxembourgish keep the case: on the
  simulator de_DE accepts "auto" and "haus", so the name guard can't protect
  their nouns. A language with no dictionary keeps the case too.
- README: the rule.

Verified: xcodebuild test on the iPhone 18 Pro simulator, 213 tests pass (1
skipped as before), with new tests for the sentence-start rule, the
exceptions, spacing, and the language-to-dictionary mapping. A temporary,
uncommitted test on the simulator's real UITextChecker found "sarah" and
"london" unknown and "the"/"that's" known in en_US, es and de_DE. How each
host app reports documentContextBeforeInput is unverified on a device.

* iOS: push to talk on the Hex key and the dictation bar's Dictate

A tester asked to hold to talk instead of tapping Dictate and then Done.

Rule: holding still for 0.35 s (HexKeyGesture.holdDuration, the Hex key's
existing hold) starts dictation at once, and lifting the finger finishes it
as Done does. A quick tap keeps tap to start, Done to finish. On the Hex key,
sliding more than 10 pt before the hold fires still opens the style menu;
once dictation has started, moving changes nothing. Push to talk applies
only when dictation runs in the keyboard (warm session or in-keyboard
dictation); a hold that opens Hex stays a tap.

- HexKeyGesture: a fired hold's touch-up is now .release (was ignored).
  Changed: before, a hold started dictation and the release did nothing.
- HexKeyControl calls onHoldRelease; FullKeyboardView finishes the dictation
  the hold started (model.onStopTap, logged as dictation_stop from
  hex_key_release). The recording fade keeps a still-tracking Hex key in
  the window at alpha 0 instead of hiding it, so its touch keeps arriving.
- KeyboardSurfaceView: the well tracks the press with a simultaneous
  DragGesture on the same state machine (the Dictate button stops taking
  touches once recording shows), starts with the light haptic
  (onKeyFeedback: Haptics setting and Full Access), and finishes on release;
  the button's own touch-up action skips a press the hold took.
- Accessibility hints mention holding; README and docs/typing-logs.md
  describe it.

Verified: xcodebuild test on the iPhone 18 Pro simulator, 213 tests pass (1
skipped as before), including the updated HexKeyGesture tests (hold then
release finishes; moving after the hold is ignored). The dictation bar
renders as before (--snap-state keyboard-warm). Real touches (hold timing,
the bar's buttons with the well's gesture, the Hex key's touch surviving the
recording panel) were not driven on the simulator and need a physical
iPhone.
2026-11-20 13:21:16 +00:00

15 KiB
Raw Permalink Blame History

Typing logs (Record typing logs)

Experiments › Record typing logs (off by default, App Group key experiments.typingLogs) makes Hex's keyboard write raw logs of everything it sees: every touch with its position and timing, the key it pressed, what that did to the text, the text around the cursor, and dictations. They are for testing and training keyboard prediction and per-user touch models on a Mac. Nothing is sent anywhere; Experiments › Typing logs shares a day's file (or all of them) through the share sheet, for example by AirDrop.

It is separate from Learn how I type, which keeps only word pairs and per-key averages and is unchanged.

Files

  • TypingLogs/yyyy-MM-dd.ndjson in the App Group container (group.anomaly.hex.mobile), one per local day (Gregorian date in the iPhone's time zone). Each event goes to the file of the day its t falls in.
  • NDJSON: one JSON object per line, UTF-8, \n after every line.
  • Kept 14 days (today and the 13 before). Older files are deleted when the keyboard starts a logger and when the Typing logs screen opens.
  • At most 64 MB a day. The first event that would cross the cap is replaced by one cap_reached line and nothing more is written that day.
  • The keyboard writes nothing without Full Access (it can't reach the App Group) and nothing while the experiment is off. The app's keyboard preview and simulator fixtures never write logs.

Writing: events are appended to an in-memory buffer on the main thread and handed to one serial utility queue every 2 s (and when the keyboard goes away, on a memory warning, and at 1,500 buffered events), which encodes them and appends them with FileHandle. Lines from one session are in order; a session ends with session_end unless the keyboard process was killed first.

Common fields

Every line starts with these, in this order:

key type meaning
v int Schema version, 1.
t int Wall clock, ms since 1970 (UTC).
mt number Monotonic ms (CACurrentMediaTime, time since boot without sleep). Use it for intervals; UITouch.timestamp (ts) is on the same clock.
type string Event type, below.
session string 12 hex digits, new each time the keyboard appears or moves to another field.
seq int 1, 2, 3… within a session. A gap means lines were lost (only the cap does that).

Units and spaces:

  • Positions and sizes are points in the keyboard view's coordinates: origin at the top-left of Hex's keyboard view (the suggestion strip's top edge), x to the right, y down. The strip is y 0–44 in portrait, the keys below it.
  • A rect is [x, y, width, height]. Insets are [top, left, bottom, right]. Points have 2 decimals, ms 3.
  • Character counts are Swift Characters (grapheme clusters), what one backspace removes.
  • A key id is the character itself for character keys (always one character: "a", "7", "@"; letters lowercase) and a word for the others: shift, delete, space, return, hex, globe, layer:numbers, layer:symbols, layer:letters.

Events

session_start

The keyboard appeared (trigger: appear), the field changed while it showed (field), or the experiment was turned on while it showed (enabled).

  • surface: full (Hex's keys) or bar (the dictation bar; no touches).
  • document: UITextDocumentProxy.documentIdentifier, which changes with the field. The host app is not knowable from a keyboard and is never guessed.
  • traits: keyboardType, returnKeyType, autocapitalization, autocorrection, spellChecking, smartQuotes, smartDashes, smartInsertDelete, inlinePrediction, keyboardAppearance (UIKit case names, e.g. "emailAddress", "send", "no"), textContentType (its raw value or null), secure, enablesReturnKeyAutomatically.
  • bounds [w, h] and safeArea of the keyboard's root view when the session started (may be before layout; layout lines carry the real size), orientation (portrait/landscape), appearance (light/dark).
  • device (iPhone17,1; Simulator:… in the simulator), system (iOS 26.1), version and build of Hex, locale, languages (first four preferred), keyboardLanguage (the keyboard's primaryLanguage), inputMode (the field's input mode language), fullAccess.
  • settings: autocorrect (Hex's), key_popups, haptics, learnHowIType, cleanupTagger, hexKeyPlacement, dictationLanguage (BCP 47, or automatic), keyboardLayout (en/nb/es/de, empty for the dictation bar), style (dictation style).

A context line follows at once with the text already in the field.

skipped

Instead of session_start in a field that must not be logged; nothing else is written for that session, not even session_end. reason is secureTextEntry or textContentType:<raw value> for password, newPassword, oneTimeCode and every creditCard… content type. Also trigger, surface, keyboardType, textContentType, secure. Every other field is logged, including ones with autocorrection off.

session_end

reason: disappear, field_changed, disabled, or replaced. durationMS, and counts of touches (began), edits, dictations. A context line (when the text changed since the last one) and any unwritten candidates come just before it.

layout

Written when the key layout or shift changes, and when a session starts.

  • hash: 16 hex digits over every key's id, frame and hit frame and the strip. Touches name it in layout.

  • cause: session, field, layout (width, orientation, globe), geometry (view size or safe area only), layer_key (123/#+=/ABC pressed), layer_auto (space or return went back to letters), layer_slide (hold 123, slide, let go), shift_key, typed (a one-shot shift turned off), auto (auto-capitalization), cancel, language (the keyboard layout changed).

  • layer (letters/numbers/symbols), shift (off/on/locked), shiftHeld (only when true), field (text/url/email), orientation, width, height (the keys' layout), view [w, h], safeArea, horizontalInset (landscape), globe, hexPlacement, language (en/nb/es/de).

  • The first time a hash appears in a day's file the line also has:

    • letterWidth (a 10-key row's; 11-key Norwegian and German letters are narrower, see keys), metrics (side, gap, rowGap, keyHeight, stripHeight, keysBottom, cornerRadius),
    • strip: the suggestion strip's rect, and slots: its three suggestion slots (left, centre, right),
    • keys: [{id, label, row, frame, hitFrame}]. frame is the drawn keycap, hitFrame the touch target; hit frames tile the key area (row 0 to 3) with no gaps. The Hex key in the strip has row -1.

    Later lines with the same hash in that file say "repeat": true instead, so look the keys up by hash. Every touch's hash appears in full earlier in the same file.

touch

One finger sample on the keys (not the strip, whose buttons log ui/edit).

  • phase: began, moved, ended, cancelled. id: the finger, stable from began to ended.
  • x, y: the raw touch location. r: majorRadius, rt: majorRadiusTolerance (pt). force and maxForce only on devices with force. ts: UITouch.timestamp in ms (monotonic, same clock as mt).
  • layout: the layout hash at the time.
  • key: the key the engine resolves. For began, the key under the point (what the engine presses). For moved and ended, the key the finger is held on: sliding across character keys moves it; any other key keeps the key it went down on. null when the finger went down outside every key.
  • under: on moved/ended/cancelled, the key under the raw point when it differs from key (null: outside every key). The engine has no touch correction model today: it uses the hit frames, so key on began always equals the key under the point.
  • moved is throttled: a sample is written once the finger has moved at least 2 pt and 8 ms since the last line for it, or when it slides onto another key.

Order: began and ended lines come before the edits they cause (a character types on release; delete and shift act on press; a press commits the characters of fingers still down, which is rollover). A moved line comes after what the move did (trackpad cursor steps, accent selection).

edit

What the keys did to the text, with op. To rebuild the text before the cursor, for every edit (and dictation) line remove deleted (a string; deletedCount characters when the text wasn't known) from the end, then append inserted. cursor moves need the context lines to resync.

op fields
insert inserted, src: key (a character or space), accent (long-press pick), slide (hold 123, slide, let go), bar (the dictation bar's space)
delete deleted (the character), src: key (on press), repeat (held, 75 ms), repeat_fast (after 0.85 s, two at a time), bar
delete_word deleted, src: repeat_word (held past 1.4 s)
autocorrect from, to, deleted (= from), inserted (to + space). Applied on space.
autocorrect_undo deleted (the correction and its space), inserted (what was typed): one backspace right after a correction undid it.
suggestion slot (0 left, 1 centre, 2 right), text (as shown), deleted (the word being typed), inserted (the replacement + space), candidates (as in candidates)
double_space_period deleted: " ", inserted: ". "
return inserted: "\n", returnKeyType, send (the key said Send); ignored: true and no inserted when the key was disabled (empty field)
paste inserted: the strip's Paste chip
undo_dictation deleted (the dictation), or deletedCount when the host showed only its end
cursor offset: characters the spacebar trackpad moved the cursor (negative is left)

candidates

The suggestions the strip offers: items: [{slot, text, replacement?, kind, auto?}], kind literal (left, what you typed), primary (centre; auto: space will apply it), secondary. Written only when they changed, lazily: just before the next touch goes down and at session end, so each line is what was on screen when a finger next went down. The strip hides them while it shows Undo dictation, a status, or the clipboard chips.

context

The host's text around the cursor, as documentContextBeforeInput / AfterInput give it. why: session_start, space, return, suggestion, delete_word, autocorrect_undo, paste, trackpad, undo_dictation, dictation, session_end, or text_did_change (the host changed the text or moved the cursor: written once things settle for 0.3 s, at once when the field emptied). before (the last 200 characters), after (the first 200), beforeLength and afterLength (before capping; hosts often cut the context short themselves), hasText. cleared: true when the field had text and now has none (most apps clear it when they send). An unchanged context is not written again.

ui

Taps that aren't text: action:

  • accent_open (id, key, options), accent_pick (id, index, chosen, rollover when another key committed it), accent_cancel;
  • trackpad_start (id), trackpad_end (id, offset: total characters);
  • hex_key (dictation: warm, keyboard, open_hex), hex_menu, style (style, from: hex_menu or recording_panel), return_app (app), dictation_language (language: BCP 47 or automatic, from the Hex menu), dictation_stop (from: hex_key_release when lifting a push-to-talk hold ends it), dictation_cancel;
  • next_keyboard (strip chip), globe, undo_dictation (applied: false when the text had changed), touches_cancelled (count).

dictation

Hex inserted a dictation (from the full keyboard or the dictation bar).

  • source: keyboard (in-keyboard dictation) or app (a warm session or a handoff to Hex). resultID, style.
  • Each step, when it ran (a step that didn't run is missing): engine, locale (in-keyboard) or language (the app), recordedMS, transcribeMS, raw (as heard), fixed (after Learn how I type's fixes), spelled (after custom vocabulary, app), tagged (after Clean up what I say), cleaned (after Apple Intelligence, app), translated, formatted (after the style, app).
  • text: the transcript Hex delivered; inserted: what went into the field (with the spacing TranscriptFormatter.insertionText added).

A context line follows.

dictation_outcome

What became of a dictation, from DictationEditTracker (the same inference Learn how I type uses, run separately). dictationSession and dictation (its seq) name the dictation line it is about. outcome: kept, edited, rewritten, undone, deleted, redictated. words, changed, pairs: [{kind, heard, inserted, meant, before, after}]. It settles within 60 s, when the keyboard goes away or moves to another field, or on a Send return key, so it can be in a later session than its dictation.

cap_reached

The day's file hit 64 MB. bytes (file size before this line), cap; seq and session are those of the first event not written.

Size and cost

Measured in the simulator (Debug build, TypingLogTests.testLoggingOverheadAndSize, 3,000 taps of ordinary words): about 1 KB per tap, about 5.2 lines (a began, one moved, an ended, an edit, a candidates, plus a context per word and a layout when shift changes). Steady typing at 200 characters a minute is about 12 MB an hour, so the 64 MB cap is about 5 hours of nonstop typing in a day. On the main thread logging added about 12 µs per tap (35 µs without it, 48 µs with); encoding and appending run on the utility queue. Real fingers may produce more moved lines than the test's one per tap.

Reading a day on a Mac

import json
layouts, text = {}, ""
for line in open("2026-11-19.ndjson"):
    e = json.loads(line)
    if e["type"] == "layout" and "keys" in e:
        layouts[e["hash"]] = e["keys"]
    elif e["type"] in ("edit", "dictation"):
        if "deleted" in e: text = text[: len(text) - len(e["deleted"])]
        elif "deletedCount" in e: text = text[: len(text) - e["deletedCount"]]
        text += e.get("inserted", "")
    elif e["type"] == "touch" and e["phase"] == "ended":
        keys = layouts[e["layout"]]   # where the finger lifted, against every key's frame

(Python counts code points, not grapheme clusters; use a grapheme library for emoji and combining marks.)