Skip to content

Recover Vial unlock sessions after reconnect#83

Open
IgorArkhipov wants to merge 3 commits into
ergohaven:mainfrom
IgorArkhipov:igor/vial-unlock-resume-recovery
Open

Recover Vial unlock sessions after reconnect#83
IgorArkhipov wants to merge 3 commits into
ergohaven:mainfrom
IgorArkhipov:igor/vial-unlock-resume-recovery

Conversation

@IgorArkhipov

@IgorArkhipov IgorArkhipov commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

EN

Problem

Diagnostic logs captured Phenom Mini freezes with VIA protocol 0 while Vial protocol 6 and keyboard ID remained valid. A hardware reset restored VIA protocol 9. This state matches firmware remaining inside a Vial unlock session, where normal keyboard input is suppressed until unlock finishes or firmware resets.

Entropy rejected this state as unsupported during reconnect, before checking Vial unlock status. It could also start the blocking firmware session without a deliberate unlock action because opening a locked Matrix Tester or macro flow immediately sent UNLOCK_START.

Fix

  • Treat VIA 0 as recoverable only when Vial reports unlocked = false and in_progress = true; every other unsupported VIA response remains an error.
  • Load the keyboard definition through commands allowed during active unlock, restore the highlighted-key overlay, and continue UNLOCK_POLL without sending another UNLOCK_START.
  • Reload full keyboard state after recovery completes or firmware reports that the session ended.
  • Require an explicit Start click before beginning a new unlock. Cancel before Start only closes the prompt; an active firmware session stays visible because Vial provides no cancel command.
  • Log protocol detection, explicit start, resume, completion, and reconnect transitions for future diagnostics.

This closes Entropy-controlled triggering and reconnect recovery. A firmware timeout/watchdog for host loss remains separate firmware work.

Verification

  • cargo test --locked: 194 passed.
  • cargo build --locked --release: passed on macOS.
  • cargo clippy --locked --all-targets: passed with existing repository warnings.
  • python3 scripts/check_i18n.py: passed.
  • Scoped rustfmt --check and git diff --check: passed.
  • Physical Phenom Mini validation was not available locally.

Post-Deploy monitoring & validation

  • On a locked Phenom Mini, open Matrix Tester: the prompt may open, but keyboard input must continue until Start is clicked.
  • Start unlock, then suspend, reconnect, or relaunch Entropy before completing it. Entropy must restore highlighted keys, finish unlock without another UNLOCK_START, and reload full keyboard state.
  • Inspect logs for VIA protocol 0 received, Recovering active Vial unlock, Vial UNLOCK_START accepted, and Reloading device state after Vial unlock recovery. Repeated recovery loops or VIA 0 without active Vial status are rollback signals.
  • Validation window: next 0.2.x prerelease and first 24 hours after release. Owner: Entropy maintainers. Rollback: revert this commit or ship the previous Entropy build; keep firmware watchdog work separate.

Related: #68

RU

Проблема

https://t.me/c/1464748383/7588/130869

Диагностические логи зафиксировали зависание Phenom Mini: VIA protocol возвращал 0, при этом Vial protocol 6 и keyboard ID читались корректно. После аппаратного сброса VIA protocol снова стал 9. Такое состояние соответствует незавершенной Vial unlock session в прошивке, во время которой обычный ввод с клавиатуры заблокирован до завершения unlock или сброса прошивки.

При reconnect Entropy отклоняла это состояние как неподдерживаемое до проверки Vial unlock status. Кроме того, открытие заблокированного Matrix Tester или macro flow сразу отправляло UNLOCK_START, поэтому блокирующая firmware session могла начаться без явного действия пользователя.

Исправление

  • VIA 0 считается восстанавливаемым только если Vial сообщает unlocked = false и in_progress = true; остальные неподдерживаемые ответы VIA остаются ошибкой.
  • Entropy загружает keyboard definition через команды, разрешенные во время активного unlock, восстанавливает экран с подсвеченными клавишами и продолжает UNLOCK_POLL без повторного UNLOCK_START.
  • После завершения recovery или окончания firmware session Entropy заново загружает полное состояние клавиатуры.
  • Новый unlock начинается только после явного нажатия Start. Cancel до Start только закрывает prompt; активная firmware session остается видимой, потому что Vial не предоставляет команду cancel.
  • В логи добавлены обнаружение протокола, события start, resume, completion и reconnect transitions.

Это закрывает запуск блокирующего состояния и reconnect recovery со стороны Entropy. Firmware timeout/watchdog при потере host остаётся отдельной задачей прошивки.

Проверка

  • cargo test --locked: прошли 194 теста.
  • cargo build --locked --release: прошёл на macOS.
  • cargo clippy --locked --all-targets: прошёл с существующими предупреждениями репозитория.
  • python3 scripts/check_i18n.py: прошёл.
  • Scoped rustfmt --check и git diff --check: прошли.
  • Физическая проверка на Phenom Mini локально не выполнялась.

Проверка после билда

  • На заблокированной Phenom Mini открыть Matrix Tester: prompt может открыться, но клавиатура должна продолжать работать до нажатия Start.
  • Начать unlock, затем усыпить Mac, переподключить клавиатуру или перезапустить Entropy до завершения. Entropy должна восстановить подсвеченные клавиши, завершить unlock без повторного UNLOCK_START и заново загрузить полное состояние клавиатуры.
  • В логах проверить VIA protocol 0 received, Recovering active Vial unlock, Vial UNLOCK_START accepted и Reloading device state after Vial unlock recovery. Повторяющийся recovery loop или VIA 0 без активного Vial status требуют rollback.

@kissetfall kissetfall left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Two blockers remain on the current main integration.

  1. The recovery path cannot currently observe VIA protocol 0. Since #92, read_response validates reports on every transport through response_matches_command. The CMD_VIA_GET_PROTOCOL_VERSION matcher only accepts protocol 9 or 0xFFFF, so the echoed 0 response produced while Vial unlock is active is discarded and get_protocol_version() fails before classify_via_connect() runs.

Please fix this in the HID response-matching owner rather than bypassing validation in the connect task. Preserve stale/unrelated-report rejection, and add a regression test that covers the actual chain: the active-unlock VIA 0 response is accepted by the matcher and then classified as recovery only after get_unlock_status reports (unlocked = false, in_progress = true).

  1. The new overlay actions use default egui::Ui::button controls and place the positive action before the negative action. Entropy's UI contract requires the shared modern_button control and negative/backward actions first. Please render Cancel before Start using the reusable button helper.

After these code fixes, this PR still needs the physical Phenom Mini scenario before merge: opening the prompt must not send UNLOCK_START; reconnecting during an active session must resume without a second UNLOCK_START; completion must reload the full keyboard state.

@IgorArkhipov
IgorArkhipov force-pushed the igor/vial-unlock-resume-recovery branch from 1084b5d to 6335067 Compare July 18, 2026 18:02
@IgorArkhipov

Copy link
Copy Markdown
Contributor Author

Addressed in commit 6335067 and rebased onto current main.
VIA protocol 0 now passes normal response matching only for valid protocol-version replies, then recovers only when unlock status confirms an active session.
Also updated overlay controls to shared Cancel then Start buttons.
Cargo test passes.
Physical Phenom retest remains before merge. Could run it on Monday.

@kissetfall

Copy link
Copy Markdown
Member

Re-reviewed head 6335067 against current main.

Both requested code blockers are resolved:

  • VIA protocol 0 is accepted in the HID response-matching owner only for a structurally valid protocol reply, then classified as recovery only when unlock status confirms an active session.
  • Overlay actions use the shared modern_button control in Cancel → Start order.

The recovery path resumes polling without a second UNLOCK_START and reloads the full device state on completion. Local validation passed: 219/219 tests, Clippy, i18n, scoped rustfmt, git diff --check, and release build. CI is 4/4 green. I found no new code blocker.

Keeping the existing CHANGES_REQUESTED until the planned physical Phenom Mini retest. Please post the results for these scenarios:

  1. Opening the unlock prompt does not send UNLOCK_START before Start is clicked.
  2. Reconnect during an active session resumes it without a second UNLOCK_START.
  3. Completion reloads the full keyboard state without a recovery loop.

After a successful hardware check, this is ready for approval.

@IgorArkhipov
IgorArkhipov force-pushed the igor/vial-unlock-resume-recovery branch from 6335067 to e81fc15 Compare July 18, 2026 19:56

@kissetfall kissetfall left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The latest head addresses the previous code review findings: the VIA protocol 0 response now passes the HID matcher before classification, and the unlock prompt uses the standard controls in Cancel → Start order.

Two requirements remain before merge:

  1. Rebase onto the current main branch and resolve the content conflict in src/ui/device_connect_task.rs, preserving the current asynchronous connection and write-state changes from main.
  2. Validate the recovery flow on a physical Phenom Mini:
    • opening and cancelling the prompt must not send UNLOCK_START;
    • reconnecting during an active unlock must resume polling without a second UNLOCK_START;
    • completing the recovered session must reload the full keyboard layout and settings.

Local result on the current PR head: 226/226 tests pass and the changed Rust files pass rustfmt. Please re-request review after the rebase and hardware smoke test.

@IgorArkhipov
IgorArkhipov force-pushed the igor/vial-unlock-resume-recovery branch from e81fc15 to 06fa3f5 Compare July 24, 2026 07:18
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