Skip to content

fix: force utf-8 output from windows powershell print helpers - #802

Merged
khaira777 merged 3 commits into
mainfrom
fix/790-windows-print-unicode
Sep 21, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fix/790-windows-print-unicode

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Problem

Windows printer support reports from Spanish- and Portuguese-language systems contain Unicode replacement characters in PowerShell diagnostics (Excepci?n, m?dulos). The corruption is already present in the submitted support message, so it affects both the UI printer error and the support ticket payload. Reported on receipt and KOT Windows raw-spooler paths, FloCafe 3.5.1 - 3.8.1.

Fixes #790

Confirmed root cause

main/printers/thermal.ts builds both Windows PowerShell helpers and runs them as:

const encoded = Buffer.from(WINSPOOL_HELPER_SCRIPT, 'utf16le').toString('base64');
await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { encoding: 'utf8', ... });

Two independent facts produce the lossy result:

  1. The child's output encoding is never specified. Windows PowerShell 5.1 renders redirected stdout/stderr through its console host using the console/OEM code page (e.g. CP850/CP1252 on Spanish and Portuguese installs), not UTF-8. The helper only sets $ErrorActionPreference, never a stream encoding.
  2. Node always decodes with encoding: 'utf8'. Single-byte 0xF3 (ó) is not valid UTF-8, so Node replaces it with U+FFFD. This is irreversible by the time sanitizePowerShellStderr() sees the string - no downstream sanitization can restore the character, which matches the issue's "cannot be recovered" note.

The corrupted text that reaches users is the helper's own thrown exception message (Excepción al llamar a SendRaw) plus the PowerShell progress record Preparing modules for first use, which is localized and is framing rather than a device reason.

What changed

main/printers/thermal.ts:

  • Added POWERSHELL_UTF8_PRELUDE, prefixed to both helper scripts (detection and raw print) through a new windowsPowerShellCommandArgs(script) builder, so there is a single place where the transport contract is defined:
    • $ProgressPreference = 'SilentlyContinue' removes the localized "Preparing modules for first use" progress framing that was polluting printer errors.
    • A System.Text.UTF8Encoding writer is installed over [Console]::OpenStandardOutput() / [Console]::OpenStandardError() with AutoFlush, and [Console]::OutputEncoding is set, so the helper releases UTF-8 bytes even on a non-UTF-8 console code page. The whole block is wrapped in try { } catch { } on purpose: it is best-effort and can never break printing or change control flow.
  • Both helpers now [Console]::Error.Flush() before exit 1 so the localized reason is not lost at process teardown.
  • The two call sites now share the same builder instead of duplicating the -EncodedCommand construction.

Why this is the smallest safe fix

  • It is exactly acceptance criterion 1 ("the Windows helper explicitly uses a known Unicode encoding for stdout and stderr") and criterion 2 (progress framing removed) without touching sanitizePowerShellStderr(), classifyPrintFailure(), the printing flow, the API contract, or the support pipeline.
  • No dependency, no new module, no reformatting; the prelude is defined once and applied to the only two powershell call sites in main/ (verified with a repo-wide search).
  • Node's encoding: 'utf8' was already correct given a UTF-8 producer, so the decoder was left alone rather than adding a code-page detection layer.

Reproduction before the fix

Windows PowerShell 5.1 is not available on the development machine (macOS), so the failure was reproduced at the byte boundary instead of on a Spanish Windows host, using the real printViaUSB() transport with a stub powershell on PATH that writes exact bytes to stderr:

  • Red state (fix reverted, tests present): FLO_FAKE_PS_STDERR_PAYLOAD bytes are decoded as UTF-8 while the transmitted script has no stream contract, so the new suite fails on the helper switches its writers to UTF-8 with AssertionError [ERR_ASSERTION], and the diagnostics assertions cannot hold.
  • Case 4 of the new suite also pins the actual defect: legacy single-byte Excepción (0xF3) fed through the boundary comes back containing U+FFFD - the corruption is irreversible, which is why the producer must be fixed and not the decoder.

Limitation stated plainly: no run on a real Windows PowerShell 5.1 host was performed in this environment.

Verification after the fix

Check Result
npx ts-node --transpile-only -P tests/tsconfig.json tests/windows-print-stderr.test.ts pass (red before, green after)
npm run test:printer (includes test:printer-api, test:printer-ipc) pass, 423 + 60 + IPC assertions
npm run test:thermal-capabilities pass
npm run test:print-document pass (29)
npm run test:print-kernel pass (14)
npm run lint pass (0 errors; pre-existing warnings only)
npm run build pass
git diff --check clean

Not run: full npm test (150+ suites, disproportionate to a two-file printing change) and no run on real Windows PowerShell 5.1 hardware.

Regression tests added (tests/windows-print-stderr.test.ts)

The existing cases all start from JavaScript strings, which is what hid the bug. The new runEncodingRegression() block drives the real subprocess boundary:

  • Accented Spanish (Excepción ... SendRaw) and Portuguese (Não foi possível ... economizado) UTF-8 bytes written to stderr reach detail byte-for-byte, with explicit assertions that neither U+FFFD nor ? substitution appears.
  • The same strings inside CLIXML framing (including _x000D__x000A_ escapes) survive the existing framing cleanup with accents intact.
  • English diagnostics and classification are unchanged (Printer is offline -> failureClass: "offline").
  • The bytes the transport actually sends carry the UTF-8 stream contract for stdout and stderr, ordered before the helper reads its inputs, and are clean ASCII themselves.

Existing sanitizePowerShellStderr() / classifyPrintFailure() cases were left untouched and still pass.

Risk notes

  • The UTF-8 prelude cannot change control flow or exit codes: every statement is inside try { } catch { }.
  • printViaUSB() is covered through both receipt and KOT dispatch, so both reported surfaces share the corrected transport.
  • A future merge conflict with concurrent edits to main/printers/thermal.ts is possible but the change is confined to one prelude constant, one builder, two call sites, and two flush lines.

Windows PowerShell 5.1 writes redirected stdout/stderr using the console/OEM code page, so FloCafe's UTF-8 decode turned accented diagnostics from Spanish and Portuguese systems into replacement characters before they reached the UI and support tickets. The raw-print and detection helpers now install UTF-8 stream writers (and the console output encoding where one exists) before doing any work, and silence the module-loading progress record that only added localized framing to printer errors.

Fixes #790
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 23 seconds.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: de196fe1-b3d3-4d5b-8c41-326636c160c2

📥 Commits

Reviewing files that changed from the base of the PR and between 322694e and 96a2dee.

📒 Files selected for processing (2)
  • main/printers/thermal.ts
  • tests/windows-print-stderr.test.ts

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

Comment @coderabbitai help to get the list of available commands.

@itoqa

itoqa Bot commented Sep 21, 2026

Copy link
Copy Markdown

Ito QA test results
Commit: 3bf0dfa: 7 test cases ran, 7 passed ✅.

Summary

Coverage spans Windows printing behavior across successful jobs, offline and setup-failure handling, printer detection, concurrent requests, command encoding, and readable accented error messages. It includes normal flows plus edge cases around failures, concurrency, Unicode text, and preserving useful printer details, with no application regressions identified.

Safe to merge — the exercised printing and detection behaviors are healthy, and no failures are attributable to this PR. The observed environment limitation around live offline printing is not a merge blocker.

Tests run by Ito

View full run

Result Severity Type Description
✅ — General Two print requests completed without mixing their printer names, payload files, or UTF-8 error messages.
✅ — Detection The detection endpoint returned HTTP 200 with valid JSON instead of failing. The empty printer list came from the recorded non-Windows host, which does not run the Windows PowerShell detection branch.
✅ — Diagnostics Failed Windows print responses kept the original Spanish and Portuguese accents, and PowerShell framing was removed.
✅ — Diagnostics The failed print response kept the accented error text and removed the PowerShell wrapper lines.
✅ — Printing The successful Windows print contract passed. The response path reports success and the parser keeps the job ID, driver name, and printer status returned by the spooler helper.
✅ — Printing The live offline print check was blocked because the local app stopped during restart, but the focused regression suite passed the Windows failure path and its offline classification.
✅ — Rev Both printer commands include the shared UTF-8 setup before their helper code. They also keep the required no-profile and non-interactive options.

Tip

Reply with @itoqa to send us feedback on this test run.

@khaira777 khaira777 changed the title fix: force utf-8 output from windows powershell print helpers (#790) fix: force utf-8 output from windows powershell print helpers Sep 21, 2026
@khaira777
khaira777 enabled auto-merge (squash) September 21, 2026 05:34
@khaira777
khaira777 merged commit b56bb5f into main Sep 21, 2026
15 checks passed
@khaira777
khaira777 deleted the fix/790-windows-print-unicode branch September 21, 2026 05:40
@itoqa

itoqa Bot commented Sep 21, 2026

Copy link
Copy Markdown

Ito QA test results
Ito Diff Report — 3bf0dfa → 96a2dee: 16 test cases ran, 16 passing ✅.

Diff Summary

Coverage focused on business rules and edge-case failure handling: printer errors remain useful, bounded, and free of sensitive command or file-path details, while printer metadata and order-support classifications remain intact. Live checkout and POS behavior was largely unavailable because the application remained in first-run setup, so those user flows were not fully exercised.

Safe to merge — no regressions, new failures, or PR-attributable still-failing tests were identified, and the focused behavior checks passed. The setup-blocked checkout and POS observations are environment limitations rather than merge blockers and can be flagged for follow-up.

Tests run by Ito

View full run

Result State Severity Type Description
✅ Passing — General The discount recovery check could not start because the local app opened its first-time setup screen instead of checkout. No order, bill, discount, or payment was changed, so this run found no product failure.
✅ Passing — General The focused Windows printer check kept useful error text and stable failure labels without exposing encoded commands, temporary file paths, or oversized diagnostics. The live API attempt was blocked because this Linux server used its CUPS path instead of the Windows printer path.
✅ Passing — Checkout The checkout could not be opened because the local app stayed on its first-run setup screen. Source inspection confirms that a legacy attempt owned by another cashier is treated as not mine and is left in place.
✅ Passing — Detection The local printer stub returned a named printer and localized progress text, but the app could not reach the authenticated detection flow. The frontend returned 404, the backend rejected the seeded session, and the browser stayed on setup, so this run does not show a product failure.
✅ Passing — Diagnostic Windows printer failures are classified clearly, and diagnostic messages do not expose encoded commands or temporary file paths.
✅ Passing — Diagnostic A failed Windows printer action kept useful error text, replaced the temporary file path, and capped the message at 400 characters.
✅ Passing — Failure The live printer request could not test Windows because the server was running on Linux, but the focused Windows check passed. It kept useful error details, removed command and temporary-file data, and limited long diagnostics.
✅ Passing — Order The order retry could not be run because the app opened its first-run setup screen instead of the point-of-sale screen. The local backend had no seeded users, so no product, cart, or order request could be created.
✅ Passing — Order The test could not reach the order screen because the required local app showed first-run setup instead. No order request was made, so this run provides no evidence of a product failure.
✅ Passing — Printer Printer detection returned both named devices with their USB type, driver, status, default setting, and paper width intact.
✅ Passing — Printing The browser could not reach the printer settings because the required site served only the frontend and redirected to first-run setup. The printer service was on a separate local port, which this test was not allowed to use.
✅ Passing — Rev The local app stayed on the setup screen, so the POS retry scenario could not be exercised. Setup completion failed because the running app returned 404 for its setup status and initialization requests.
✅ Passing — Rev Printer settings could not be opened because local setup failed, so the discovery action was not run. Source inspection shows the discovery path returns safely and logs only sanitized, bounded failure details.
✅ Passing — Rev The POS could not open because the local setup check and setup initialization requests returned 404. The order failure panel and support request were not reached, so this run does not show a product failure in the order-support behavior.
✅ Passing — Support The order support check could not reach the POS because the local app was missing its setup, authentication, and order API routes. The repository contains the expected failure-panel and payload-safe support flow, so this result is recorded as a local environment reclassification rather than a product failure.
✅ Passing — Support The order flow has separate, payload-free codes and details for server rejection, unreachable transport, and other local failures. The local POS was unavailable during the browser run, so the three live cases could not be exercised there.
⏸️ Skipped — General Two print requests completed without mixing their printer names, payload files, or UTF-8 error messages.
⏸️ Skipped — Detection The detection endpoint returned HTTP 200 with valid JSON instead of failing. The empty printer list came from the recorded non-Windows host, which does not run the Windows PowerShell detection branch.
⏸️ Skipped — Diagnostics Failed Windows print responses kept the original Spanish and Portuguese accents, and PowerShell framing was removed.
⏸️ Skipped — Diagnostics The failed print response kept the accented error text and removed the PowerShell wrapper lines.
⏸️ Skipped — Printing The live offline print check was blocked because the local app stopped during restart, but the focused regression suite passed the Windows failure path and its offline classification.

Tip

Reply with @itoqa to send us feedback on this test run.

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: Windows printer diagnostics corrupt non-ASCII PowerShell output

1 participant