Skip to content

fix(fonts): prefer pwsh and log failures in Windows font enumeration - #11785

Closed
umi008 wants to merge 1 commit into
stablyai:mainfrom
umi008:fix/issue-11771-windows-font-picker
Closed

umi008 wants to merge 1 commit into
stablyai:mainfrom
umi008:fix/issue-11771-windows-font-picker

Conversation

@umi008

@umi008 umi008 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #11771

When Group Policy blocks Windows PowerShell 5.1, the font picker silently degraded to the 5 hardcoded fallback fonts. listWindowsFonts() spawned powershell.exe by bare name, which fails with spawn UNKNOWN (errno -4094) on a GP-blocked host — and the error was swallowed by the fallback path with no log.

This PR:

  • Tries pwsh.exe first, then the absolute Windows PowerShell 5.1 path (resolved from %WINDIR%, defaulting to C:\Windows) — so the enumeration survives GP policy and also works on PowerShell 7-only installs.
  • Logs the real spawn error with console.warn before falling back, so silent degradation is now visible in the main-process log.
  • Keeps the existing memoization and the fallback behavior for genuinely unreachable hosts.

Screenshots

No visual change.

Testing

  • pnpm lint (full, incl. localization coverage audit)
  • pnpm typecheck (full, all three tsconfig projects)
  • pnpm test (targeted: src/main/system-fonts.test.ts 7/7 — 3 new Windows cases + updated win32 timeout case; src/main/ipc/settings.test.ts 28/28). Full suite not run locally; CI covers it.
  • pnpm build (not run; no build-affecting surface)
  • Added or updated high-quality tests (TDD: failing-then-passing, oxfmt/oxlint clean)

AI Review Report

Reviewed by a reliability lens against the exact candidate diff (tests + implementation):

  • Spawn-order contract: pwsh.exe is always tried first and the chain stops on first success; the absolute 5.1 path is a fallback, so PowerShell 7-first hosts keep the faster path.
  • Failure path: when every candidate fails, the last error is rethrown after logging — the outer fallback still returns the 5-font list, preserving prior behavior while making the cause observable.
  • Timeout semantics: each candidate gets the full 15s budget; worst case before fallback is ~30s only when both shells hang (was 15s). Intentionally bounded, no shared-budget coupling.
  • Regressions: memoization untouched; execFileText signature unchanged; settings IPC consumers of listSystemFontFamilies unaffected.
  • Cross-platform: change is runtime-guarded for win32 only — the darwin (system_profiler) and linux (fc-list) paths are untouched; on non-Windows hosts behavior is byte-identical.

Security Audit

  • No new input handling, no auth/secrets, no new dependencies, no IPC surface change.
  • Commands are constructed statically and executed via execFile (no shell interpolation).
  • %WINDIR% resolution is environment-driven with a fixed safe default (C:\Windows); the candidate list contains only the two well-known Windows shells.

Notes

  • Windows-only fix, verified through mocked execFile in unit tests — no Windows host connected to validate against a real GP-blocked machine.

  • Root cause of the silent degradation: the previous catch substituted the fallback list without logging, so the failure was invisible to users and maintainers alike.

  • X: @umillann

listWindowsFonts() spawned powershell.exe by bare name, which resolves to the
5.1 launcher that Group Policy can block on managed hosts, silently degrading
the font picker to 5 hardcoded fallbacks. Probe pwsh.exe first, then the
absolute Windows PowerShell path, and log the real spawn error before the
fallback.

Verified with 3 new tests (candidate chain order, absolute-path fallback,
all-fail logging) plus updated win32 timeout semantics; oxlint and oxfmt
clean.
@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a silent degradation on Windows where Group Policy blocking powershell.exe caused font enumeration to quietly return 5 hardcoded fallback fonts with no log. The fix introduces a candidate-chain approach that tries pwsh.exe first, then the absolute PowerShell 5.1 path, and emits a console.warn before re-throwing so the failure is now visible in the main-process log.

  • Spawn order: pwsh.exe is preferred (PowerShell 7), with %WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe as the fallback; PATH resolution no longer determines the outcome.
  • Timeout budget: each candidate gets its own 15 s budget, so the worst-case wait before fallback doubles to 30 s on Windows (only when both shells hang).
  • Tests: three new unit tests cover the happy path (pwsh succeeds), the cascade path (pwsh absent, absolute path succeeds), and the all-fail path (fallback fonts + warn log verified).

Confidence Score: 4/5

Safe to merge. The change is Windows-only and runtime-guarded; macOS and Linux paths are byte-identical. The candidate chain is constructed from static, trusted values with no shell interpolation.

The implementation is correct and well-tested. The only notable fragility is that execFileTextFirst would throw undefined if passed an empty commands list, though this cannot happen through the current call site. The win32 worst-case fallback latency doubles to 30 s (both shells hanging), which is documented and intentional. All other memoization and IPC paths are untouched.

Files Needing Attention: No files require special attention. src/main/system-fonts.ts is the only changed implementation file and its new helpers are straightforward.

Important Files Changed

Filename Overview
src/main/system-fonts.ts Adds windowsPowerShellCandidates() and execFileTextFirst() to try pwsh.exe before the absolute PowerShell 5.1 path; adds a logging .catch() in listWindowsFonts() that re-throws so the outer fallback still applies. One minor edge case: execFileTextFirst throws undefined if called with an empty commands list.
src/main/system-fonts.test.ts Adds three Windows-specific unit tests (pwsh success, pwsh fallback to absolute path, both-fail + warn log), updates the timeout helper to accept an expectedKills count, and adjusts the win32 timeout test to account for the new 2-candidate chain (30s total worst case).

Sequence Diagram

sequenceDiagram
    participant C as listSystemFontFamilies
    participant L as listWindowsFonts
    participant F as execFileTextFirst
    participant P1 as pwsh.exe
    participant P2 as powershell.exe (absolute)

    C->>L: (win32 only)
    L->>F: "candidates=[pwsh.exe, C:\Windows\...\powershell.exe]"
    F->>P1: execFileText(pwsh.exe, 15s timeout)
    alt pwsh succeeds
        P1-->>F: stdout
        F-->>L: output
        L-->>C: sorted font list
    else pwsh fails / GP-blocked
        P1-->>F: Error (ENOENT / UNKNOWN)
        F->>P2: execFileText(absolute path, 15s timeout)
        alt absolute path succeeds
            P2-->>F: stdout
            F-->>L: output
            L-->>C: sorted font list
        else both fail
            P2-->>F: Error
            F-->>L: throws lastError
            L-->>L: .catch() → console.warn + rethrow
            L-->>C: throws
            C-->>C: .catch() → fallbackFonts()
        end
    end
Loading

Reviews (1): Last reviewed commit: "fix(fonts): prefer pwsh and log failures..." | Re-trigger Greptile

Comment thread src/main/system-fonts.ts
Comment on lines +99 to +100
let lastError: unknown
for (const command of commands) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 execFileTextFirst throws undefined if commands is empty, because lastError is never assigned. Today windowsPowerShellCandidates() always returns two entries so this can't happen at runtime, but the contract is fragile if the function is reused or the candidates list is ever conditionally filtered. Initialising lastError to a descriptive Error makes the failure mode explicit and avoids a silent throw undefined.

Suggested change
let lastError: unknown
for (const command of commands) {
let lastError: unknown = new Error('execFileTextFirst called with empty commands list')
for (const command of commands) {

Comment thread src/main/system-fonts.ts
.catch((error: unknown) => {
// Why: a GP-blocked PowerShell used to degrade to 5 hardcoded fonts with
// no trace; surface the real spawn error so managed hosts are diagnosable.
console.warn('[system-fonts] failed to enumerate Windows fonts, using fallback:', error)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 The log message says "using fallback" but this .catch() immediately re-throws — the fallback is applied by the outer handler in listSystemFontFamilies. Someone reading the main-process log could be confused about where control actually ends up. Rewording avoids that ambiguity.

Suggested change
console.warn('[system-fonts] failed to enumerate Windows fonts, using fallback:', error)
console.warn('[system-fonts] failed to enumerate Windows fonts, falling back to defaults:', error)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Windows font discovery now tries PowerShell 7 and the absolute Windows PowerShell 5.1 executable in order. It retries candidates and returns the first successful result. If all candidates fail, it logs the spawn error and rethrows it. Tests cover successful execution, fallback execution, hardcoded fallback output, timeout behavior, retry counts, process termination, and warning output.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly describes the Windows font enumeration fix, PowerShell preference, and failure logging.
Description check ✅ Passed The description covers the summary, testing, security review, cross-platform impact, screenshots, and known build limitation.
Linked Issues check ✅ Passed The description references issue #11771 and directly addresses its Windows PowerShell and silent fallback problems.
Out of Scope Changes check ✅ Passed The changes are limited to Windows font discovery and its tests, which matches the stated objectives.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/system-fonts.ts (1)

93-108: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider bounding total worst-case wait across candidates.

execFileTextFirst gives every candidate the full timeoutMs before moving to the next one. On Windows, this doubles the worst-case wait before the fallback fonts are returned (confirmed by the test suite: 30s for two candidates vs. 15s for a single candidate on other platforms). If a Group-Policy-blocked PowerShell process hangs instead of failing fast (rather than the fast ENOENT/permission-error case), a user opening Settings on a managed Windows host now waits up to twice as long before seeing any fonts.

Split the timeout budget across candidates, or cap the total elapsed time, so adding a retry candidate does not multiply the worst-case latency.

♻️ Example: split the timeout budget across candidates
 async function execFileTextFirst(
   commands: string[],
   args: string[],
   maxBuffer: number,
   timeoutMs = SYSTEM_FONT_LIST_TIMEOUT_MS
 ): Promise<string> {
   let lastError: unknown
+  const perCommandTimeoutMs = Math.max(1, Math.floor(timeoutMs / commands.length))
   for (const command of commands) {
     try {
-      return await execFileText(command, args, maxBuffer, timeoutMs)
+      return await execFileText(command, args, maxBuffer, perCommandTimeoutMs)
     } catch (error) {
       lastError = error
     }
   }
   throw lastError
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d68de06b-0184-4ca7-8ab8-0c6dd3b3f1e6

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and e287288.

📒 Files selected for processing (2)
  • src/main/system-fonts.test.ts
  • src/main/system-fonts.ts

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 font picker silently falls back to 5 hardcoded fonts when powershell.exe is Group Policy-blocked (listWindowsFonts spawns by bare name)

4 participants