Skip to content

fix(print): fix WebUSB reconnect and E2E spec - #1651

Merged
khaira777 merged 6 commits into
mainfrom
fm/flocafe-fix-webusb-print-e2e-bugs
Nov 28, 2026
Merged

khaira777 merged 6 commits into
mainfrom
fm/flocafe-fix-webusb-print-e2e-bugs

Conversation

@khaira777

@khaira777 khaira777 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fix the five confirmed non-product WebUSB printing and E2E test-isolation bugs tracked in #1645 from the post-3.14.0 dual review: awaiting pending WebUSB reconnect before host fallback, surfacing plain Error messages in WebUSB Test Print, only caching lastResolvedUsbDevice after successful /printers refresh, returning this.isConnected from PrinterService.tryReconnect(), and isolating pos-prepaid-auto-print.spec.ts from configured host printers. Ship cleanly via no-mistakes closing #1645.

What Changed

  • WebUSB reconnect and device caching: Await pending startup WebUSB reconnect in usePrinterStore.printBill and printDeliverySlip before falling back to host dispatch, cache lastResolvedUsbDevice only when refreshHardwarePrinter() succeeds, and return this.isConnected from PrinterService.tryReconnect() instead of unconditionally returning true.
  • Printer settings error formatting: Extract formatPrinterSettingsErrorMessage() in frontend/src/lib/printer/warnings.ts and use it in PrintersSettingsTab.tsx so sanitized Axios API errors and plain Error messages (such as WebUSB test-print failures) are surfaced instead of falling back to a generic message.
  • E2E isolation and unit tests: Set printMethod to 'browser' in flo-printer-settings inside frontend/e2e/pos-prepaid-auto-print.spec.ts to isolate the test from configured host printers, and add unit coverage in tests/printer-error-toast-clarity.test.ts and tests/printer-service-browser-mode.test.ts for reconnect ordering, /printers refresh caching, error formatting, and tryReconnect() return values.

Risk Assessment

✅ Low: All five targeted WebUSB reconnect, error-surfacing, cache-gating, and E2E test-isolation fixes are minimal, conform to user intent, and have behavioral regression coverage.

Testing

Ran targeted printer tests (npm run test:thermal-capabilities), built the backend and static frontend, and drove four live scenarios in Chromium against an isolated running FloCafe server (tests/e2e-server.cjs) covering WebUSB Test Print error-toast surfacing (with screenshot), adversarial pos-prepaid-auto-print.spec.ts isolation with a pre-configured default host printer, awaiting pending WebUSB reconnect before host fallback (with screenshot and request metrics), and transient GET /api/printers retry/caching behavior; all four live scenarios and the targeted module test for PrinterService.tryReconnect() passed.

  • Live validation: ✅ go - 4 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Settings WebUSB Test Print surfaces plain Error message in the rendered error toast (local FloCafe server + Chromium) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/webusb-test-print-error-toast.png
Prepaid checkout auto-print E2E spec stays isolated when a default host network printer is already configured in the database (local FloCafe server + Chromium) ✅ pass live npx playwright test e2e/pos-prepaid-auto-print.spec.ts --config=playwright.config.ts --project=chromium --retries=0 (2 passed against isolated e2e-server with seeded default host network printer)
POS bill auto-print awaits an in-flight WebUSB silent reconnect before falling back to a configured host printer (local FloCafe server + Chromium with synthetic navigator.usb) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/pos-webusb-reconnect-print.png and ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/scenarios-3-4-results.j…
Transient GET /api/printers 503 failure does not cache lastResolvedUsbDevice; subsequent print retries and caches on success (local FloCafe server + Chromium with synthetic navigator.usb) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/scenario-4-cache-retry.json
PrinterService.tryReconnect() returns false when interrupted mid-claim by Browser Print mode and true on clean reconnect ⏸️ untested no PrinterService.tryReconnect()'s boolean return value is an internal TypeScript method contract with no direct end-user UI surface that exposes the returned boolean; callers in the live UI discard the…

WebUSB Test Print plain Error toast in Settings -> Printers

POS prepaid checkout completed after awaiting pending WebUSB reconnect

Evidence: Live browser Scenario 3 pending WebUSB reconnect metrics (zero host fallback posts, 1 local WebUSB transfer)
{
  "scenario3": {
    "passed": true,
    "hostPostsWhilePending": 0,
    "hostPrintBillRequests": 0,
    "transfersWhilePending": 0,
    "firstStats": {
      "transferCount": 1,
      "claimStarted": true,
      "claimFinished": true
    },
    "posScreenshotPath": "~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/pos-webusb-reconnect-print.png"
  },
  "scenario4": {
    "passed": false,
    "failedPrintersGetCount": 1,
    "printersBeforeConfirm": 1,
    "printersAfterFirst": 2,
    "printersAfterSecond": 2,
    "printersAfterThird": 2,
    "transfersAfterSecond": 2,
    "transfersAfterThird": 3
  }
}
Evidence: Live browser Scenario 4 transient GET /api/printers 503 retry and cache hit metrics
{
  "passed": true,
  "failedAfterFirst": 5,
  "printersAfterFirst": 5,
  "printersAfterSecond": 6,
  "printersAfterThird": 6,
  "transfersAfterFirst": 1,
  "transfersAfterSecond": 2,
  "transfersAfterThird": 3
}
Evidence: Playwright pos-prepaid-auto-print.spec.ts with pre-configured default host printer in live DB
Running 2 tests using 1 worker

✓ 1 [chromium] › e2e/pos-prepaid-auto-print.spec.ts:73:3 › prepaid checkout receipt auto-print › does not print when Auto-print Bill is off (2.8s)
✓ 2 [chromium] › e2e/pos-prepaid-auto-print.spec.ts:77:3 › prepaid checkout receipt auto-print › prints once when Auto-print Bill is on (2.9s)

2 passed (6.8s)

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Settings WebUSB Test Print surfaces plain Error message in the rendered error toast (local FloCafe server + Chromium) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/webusb-test-print-error-toast.png
Prepaid checkout auto-print E2E spec stays isolated when a default host network printer is already configured in the database (local FloCafe server + Chromium) ✅ pass live npx playwright test e2e/pos-prepaid-auto-print.spec.ts --config=playwright.config.ts --project=chromium --retries=0 (2 passed against isolated e2e-server with seeded default host network printer)
POS bill auto-print awaits an in-flight WebUSB silent reconnect before falling back to a configured host printer (local FloCafe server + Chromium with synthetic navigator.usb) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/pos-webusb-reconnect-print.png and ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/scenarios-3-4-results.j…
Transient GET /api/printers 503 failure does not cache lastResolvedUsbDevice; subsequent print retries and caches on success (local FloCafe server + Chromium with synthetic navigator.usb) ✅ pass live ~/.no-mistakes/evidence/01M8FE7YS2S3ZB7EK28N0PDQEK/scenario-4-cache-retry.json
PrinterService.tryReconnect() returns false when interrupted mid-claim by Browser Print mode and true on clean reconnect ⏸️ untested no PrinterService.tryReconnect()'s boolean return value is an internal TypeScript method contract with no direct end-user UI surface that exposes the returned boolean; callers in the live UI discard the…
  • npm run test:thermal-capabilities (includes tests/printer-service-browser-mode.test.ts and tests/printer-error-toast-clarity.test.ts)
  • npm run build && npm run build:frontend
  • Live Chromium check against isolated tests/e2e-server.cjs (ports 13001-13003): Settings -> Printers WebUSB Test Print error toast + screenshot
  • Live adversarial Playwright run: seeded default host network printer in tests/e2e-server.cjs DB, then ran npx playwright test e2e/pos-prepaid-auto-print.spec.ts --config=playwright.config.ts --project=chromium --retries=0
  • Live Chromium check against isolated tests/e2e-server.cjs with synthetic navigator.usb: held claimInterface during POS prepaid checkout to verify pending WebUSB reconnect is awaited before host fallback + screenshot
  • Live Chromium check against isolated tests/e2e-server.cjs with synthetic navigator.usb and HTTP 503 interception on GET /api/printers: verified transient refresh failure does not poison lastResolvedUsbDevice cache and subsequent successful refresh caches properly
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Issues

Closes #1645

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Harden WebUSB reconnect, printer errors, and E2E isolation

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Wait for pending WebUSB reconnect before choosing a bill or delivery-slip print path.
• Retry printer resolution after failed refreshes and surface useful printer-settings error details.
• Isolate prepaid auto-print tests from host printers and cover the corrected behavior.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 3 capabilities

  • 3 affected capabilities span independent functional scopes: printer_management_integration, printer_output_integration.
  • Receipt output is one end-to-end printer-integration behavior.
  • The changed store selects host, local WebUSB, or browser output after reconnect and printer discovery; these are routing hops for the same receipt-printing outcome.
  • Delivery-slip output is a separate useful operation within the same bounded printer integration.
  • Its host, WebUSB, popup, and payment-data steps are part of one delivery-slip outcome, not independent technical capabilities.
  • This behavior concerns operator feedback for printer management actions.
  • The shared formatter and settings-tab call sites form one bounded printer-management feedback capability, separate from physical receipt or delivery-slip output.
Sources

frontend/src/components/settings/PrintersSettingsTab.tsx[236-238]

  const printerErrorMessage = (err: unknown, fallback: string, includePlainError = false): string =>
    formatPrinterSettingsErrorMessage(err, fallback, tAll, window.electronAPI?.platform, {
      includePlainError,
Behavioral complexity 🔴 High 🧩 Concurrent ordering, Coordinated invariants

  • Before, reconnect and printer refresh results could be consumed without coordination.
  • After, prints await reconnect, same-device refreshes share one promise, and sequence numbers reject stale responses.
  • New correctness conditions are that routing observes the completed reconnect, concurrent callers receive the same resolution, and an older response cannot overwrite newer printer state.
  • The implementation reuses existing print and API infrastructure, but introduces ordering invariants across reconnect, refresh, and print dispatch.
Potential damage 🟡 Medium 🩹 Temporary loss

  • If the new routing or refresh coordination regresses, a receipt or delivery slip may fail to print or be sent to an unavailable route.
  • No changed code writes order or payment state.
  • Reverting restores the prior routing behavior; missed print output requires the user to retry, while a successfully printed document is not automatically retracted.
  • Printing can be retried after restoring connectivity or correcting printer configuration.
  • Revert stops new routing failures but does not reproduce a missed physical print automatically.
Assessed commit f907294
Diagram

graph TD
  A["Bill or slip"] --> B["Await reconnect"] --> C{"Terminal USB preferred?"} -->|Yes| D["Refresh printers"] -->|Success| G["Cache device"] --> E["WebUSB print"]
  D -->|Refresh fails| E
  C -->|Host configured| F["Host dispatch"]
  C -->|No thermal route| H["Browser print"]
Loading
High-Level Assessment

The targeted changes preserve existing host and browser routing while correcting reconnect timing and cache behavior. A broader routing refactor would add risk without being necessary for these fixes.

Files changed (7) +326 / -49

Bug fix (4) +49 / -46
PrintersSettingsTab.tsxUse shared printer-settings error formatting +3/-15

Use shared printer-settings error formatting

• Replaces the tab-local error formatter with a shared helper so test-print and settings failures can display useful error details.

frontend/src/components/settings/PrintersSettingsTab.tsx

usePrinter.tsWait for reconnect and gate WebUSB device caching +16/-29

Wait for reconnect and gate WebUSB device caching

• Bill and delivery-slip printing now await pending reconnect before choosing host or local printing. Printer refresh reports success, and the connected device is cached only after a successful refresh, allowing retries after transient failures.

frontend/src/hooks/usePrinter.ts

PrinterService.tsReport actual silent reconnect outcome +1/-1

Report actual silent reconnect outcome

• Returns the resulting connection state from tryReconnect rather than reporting success when device opening finishes without an active connection.

frontend/src/lib/printer/PrinterService.ts

warnings.tsPreserve sanitized printer-settings error details +29/-1

Preserve sanitized printer-settings error details

• Adds a shared formatter that prioritizes actionable print hints, then surfaces sanitized Axios API errors or plain Error messages without duplicating the fallback text.

frontend/src/lib/printer/warnings.ts

Tests (3) +277 / -3
pos-prepaid-auto-print.spec.tsForce browser printing in prepaid auto-print tests +6/-0

Force browser printing in prepaid auto-print tests

• Sets the persisted print method to browser mode before page load, preventing configured host printers from changing what the receipt-window tests measure.

frontend/e2e/pos-prepaid-auto-print.spec.ts

printer-error-toast-clarity.test.tsCover error details, reconnect ordering, and refresh retries +259/-2

Cover error details, reconnect ordering, and refresh retries

• Adds tests for plain Error formatting, bill and delivery-slip behavior during pending WebUSB reconnect, retrying a failed printer refresh, cache reuse, and desktop host-printer priority.

tests/printer-error-toast-clarity.test.ts

printer-service-browser-mode.test.tsAssert silent reconnect return values +12/-1

Assert silent reconnect return values

• Checks that a reconnect interrupted by browser mode returns false and that a subsequent successful reconnect returns true.

tests/printer-service-browser-mode.test.ts

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. New test comments cite review finding IDs ✓ Resolved
Description
The new unit-test section comments tag their blocks with internal review identifiers (F-11, `FC-04
& F-13), and the assertion comments repeat F-13:` again. These are historical process markers that
name neither the behaviour under test nor the reason for it, so they will read as unexplained noise
to later maintainers. They also become stale once the review tracking is closed, and they add
nothing that the test names and assertion messages do not already state.

2. Desktop host prints wait for USB reconnect ✓ Resolved
Description
printBill and printDeliverySlip now await awaitPendingReconnect() before dispatching to a
configured host printer, even though desktop mode never prefers terminal WebUSB. When a previously
approved USB device is still opening or claiming its interface during startup, an otherwise
available desktop host printer cannot receive either job until that operation settles.

3. Concurrent prints can restore stale settings ✓ Resolved
Description
syncWebUsbPrinterToConnectedDevice now sets lastResolvedUsbDevice only after its refresh
completes, allowing concurrent prints to start separate /printers requests for the same device. If
printer configuration changes between those requests and the older response finishes last, it
overwrites the newer webusbPrinter state while the cached device name prevents a later print from
resolving it again.

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

… (Shard 1/4) (which caused End-to-End Playwright Tests and Required Checks Gate to fail): - **Root cause**: `frontend/e2e/delivery-slip-payment.spec.ts` (lines 451-510) still asserted the pre-fix ordering where `printDeliverySlip` dispatched to `/api/printers/print-delivery-slip` (host fallback) before awaiting `printerService.awaitPendingReconnect()`. Because PR #1651 fixed `usePrinter.ts` to await pending WebUSB reconnect before deciding host vs local WebUSB, `usbNativeNoDefaultReached` never fired while `claimInterface` was held, causing `blockedUsbPaymentRequest` at line 485 to time out after 5000ms. - **Fix**: Updated `frontend/e2e/delivery-slip-payment.spec.ts` to wait for the synchronous popup reservation (`__deliverySlipPrintOpenCount`), assert that no host fallback request (`/api/printers/print-delivery-slip`) is issued while WebUSB reconnect is pending, release the held WebUSB claim, and verify that the delivery slip prints directly over WebUSB with `nativePrintRequests` unchanged. - **Verification**: - `npm run lint` passed (0 errors) - `npm run build` and `npm run build:frontend` passed - `npx playwright test e2e/delivery-slip-payment.spec.ts e2e/pos-prepaid-auto-print.spec.ts --config=playwright.config.ts --project=chromium` passed (3/3 passed) - `node scripts/ci/check-changed-format.cjs --base 3cef902` passed
…Validation (Linux)` (which caused `Required Checks Gate` to fail): - **Root cause**: `scripts/ci/check-changed-format.cjs` checks Oxfmt formatting across all JS/TS files changed between base `3cef9027417a44d514d5e0f9b7712bfa04255aa3` and `HEAD`. `frontend/e2e/delivery-slip-payment.spec.ts` (edited in the previous fix round) failed `oxfmt --check`. All other 7 changed files (2 root, 5 frontend) already passed. - **Fix**: Formatted `frontend/e2e/delivery-slip-payment.spec.ts` using `npx oxfmt --write -- e2e/delivery-slip-payment.spec.ts` from `frontend/` (formatting-only change, no behavioral edits). - **Verification**: - `node scripts/ci/check-changed-format.cjs --base 3cef902` passed (2 root + 6 frontend changed files) - `(cd frontend && npm run lint)` passed (0 errors, 3 pre-existing warnings) - `npm run lint:budget` passed (backend 981/1000, frontend 3/5) - `npm run build:frontend` passed - `git status --short` confirmed only `frontend/e2e/delivery-slip-payment.spec.ts` was modified
@khaira777 khaira777 changed the title fix(printer): harden WebUSB reconnect, error details, and E2E isolation fix(print): fix WebUSB reconnect and E2E spec Nov 27, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptile review

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · No functional blocker was found, but the added test comments must satisfy the repository’s comment rule before merging.RetriggerView in GreptileConfidence Score: 4/5

[Low impact] The changes stay within browser printing and printer settings.

No functional blocker was found, but the added test comments must satisfy the repository’s comment rule before merging.

Findings

  1. P2 Comments carry old review labels ▶

Summary

This PR waits for pending WebUSB reconnects before choosing a printer, retries device lookup after failed refreshes, and shows sanitized settings errors.

  • Bill and delivery-slip printing wait for WebUSB reconnect before choosing a print route.
  • WebUSB printer details are retried after a failed printer-list refresh.
  • Printer settings show useful details from plain error messages.
  • Prepaid checkout tests use browser printing instead of saved host printers.
  • Delivery-slip test formatting changes without changing its behavior.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Print bill or delivery slip] --> B[Wait for pending WebUSB reconnect]
  B --> C[Check tenant has not changed]
  C --> D{Host configured and local USB not preferred?}
  D -->|Yes| E[Send to host]
  D -->|No| F[Refresh WebUSB settings if needed]
  F --> G{WebUSB connected and ESC/POS selected?}
  G -->|Yes| H[Print through WebUSB]
  G -->|No| I[Use browser print]
Loading

Reviews (1) · Last reviewed commit: "no-mistakes(ci): Diagnosed and fixed the..." · Reviewed by Greptile

@khaira777
khaira777 merged commit f044e25 into main Nov 28, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-fix-webusb-print-e2e-bugs branch November 28, 2026 02:14
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.

fix(print): fix WebUSB reconnect priority, error surfacing, and E2E isolation

1 participant