From 17d8d079c94d4e78219115807c544bf4cbff0fd1 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 30 May 2026 11:13:04 -0700 Subject: [PATCH] fix: time out keyboard input source probe (#3812) --- src/main/ipc/app.test.ts | 35 +++++++++++++++++++++-- src/main/ipc/app.ts | 60 ++++++++++++++++++++++++++++++++-------- 2 files changed, 82 insertions(+), 13 deletions(-) diff --git a/src/main/ipc/app.test.ts b/src/main/ipc/app.test.ts index 1abd90b56..125658aca 100644 --- a/src/main/ipc/app.test.ts +++ b/src/main/ipc/app.test.ts @@ -1,10 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const { handlers, appExitMock, appQuitMock, appRelaunchMock } = vi.hoisted(() => ({ +const { handlers, appExitMock, appQuitMock, appRelaunchMock, execFileMock } = vi.hoisted(() => ({ handlers: new Map unknown>(), appExitMock: vi.fn(), appQuitMock: vi.fn(), - appRelaunchMock: vi.fn() + appRelaunchMock: vi.fn(), + execFileMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ + execFile: execFileMock })) vi.mock('electron', () => ({ @@ -35,16 +40,21 @@ vi.mock('@electron-toolkit/utils', () => ({ import { registerAppHandlers } from './app' describe('registerAppHandlers', () => { + const originalPlatform = process.platform + beforeEach(() => { vi.useFakeTimers() handlers.clear() appExitMock.mockReset() appQuitMock.mockReset() appRelaunchMock.mockReset() + execFileMock.mockReset() + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) afterEach(() => { vi.useRealTimers() + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) it('marks relaunch as expected shutdown before exiting', () => { @@ -80,4 +90,25 @@ describe('registerAppHandlers', () => { expect(appQuitMock).toHaveBeenCalledTimes(1) expect(appExitMock).not.toHaveBeenCalled() }) + + it('falls back when the macOS keyboard layout probe never reports completion', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + const killMock = vi.fn() + execFileMock.mockImplementation(() => ({ kill: killMock })) + registerAppHandlers({} as never) + + const handler = handlers.get('app:getKeyboardInputSourceId') + expect(handler).toBeDefined() + let settled = false + const resultPromise = Promise.resolve(handler?.(null)).then((result) => { + settled = true + return result + }) + + await vi.advanceTimersByTimeAsync(500) + + expect(settled).toBe(true) + await expect(resultPromise).resolves.toBeNull() + expect(killMock).toHaveBeenCalled() + }) }) diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index d24e737d6..6f6131986 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -2,7 +2,6 @@ import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' import path from 'node:path' import { pathToFileURL } from 'node:url' -import { promisify } from 'node:util' import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron' import { is } from '@electron-toolkit/utils' import type { AppIdentity } from '../../shared/app-identity' @@ -20,7 +19,7 @@ import { } from './floating-workspace-directory' import { isMarkdownDocumentName, markdownDocumentFromFilePath } from './markdown-documents' -const execFileAsync = promisify(execFile) +const KEYBOARD_INPUT_SOURCE_TIMEOUT_MS = 500 type RegisterAppHandlersOptions = { onBeforeRelaunch?: () => void @@ -100,6 +99,52 @@ function resolveDevFeatureWallAssetDir(): string { return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0] } +function readKeyboardInputSourceId(): Promise { + return new Promise((resolve, reject) => { + let settled = false + let child: ReturnType | undefined + const timer = setTimeout(() => { + if (settled) { + return + } + settled = true + child?.kill() + reject(new Error('Keyboard input source probe timed out')) + }, KEYBOARD_INPUT_SOURCE_TIMEOUT_MS) + + const settle = (callback: () => void): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + callback() + } + + // Why: execFile's timeout only signals `defaults`; if the callback + // never arrives, window-focus keyboard probes would remain pending. + try { + child = execFile( + '/usr/bin/defaults', + ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], + // Why: short timeout so a wedged defaults binary (corporate-managed + // config, sandbox policy, ...) never holds the handle indefinitely. + // Fall through to the fingerprint on timeout. + { encoding: 'utf8', timeout: KEYBOARD_INPUT_SOURCE_TIMEOUT_MS }, + (error, stdout) => { + if (error) { + settle(() => reject(error)) + return + } + settle(() => resolve(String(stdout))) + } + ) + } catch (error) { + settle(() => reject(error)) + } + }) +} + export function registerAppHandlers(store: Store, options: RegisterAppHandlersOptions = {}): void { ipcMain.handle('app:getFeatureWallAssetBaseUrl', (): string => getFeatureWallAssetBaseUrl()) @@ -132,7 +177,7 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp // have no equivalent and return null so the fingerprint stays the only // signal. // - // Why `defaults read` (via execFileSync) and not systemPreferences + // Why `defaults read` and not systemPreferences // .getUserDefault: getUserDefault only reads from NSGlobalDomain and the // current app's own domain. The keyboard layout ID lives in the // `com.apple.HIToolbox` domain, which getUserDefault cannot reach — @@ -148,14 +193,7 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp // The probe re-runs on every window focus-in (see option-as-alt-probe.ts), // and a blocking execFileSync would briefly stall unrelated IPC each // time the user Alt-Tabbed back into the app. - const { stdout } = await execFileAsync( - '/usr/bin/defaults', - ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], - // Why: short timeout so a wedged defaults binary (corporate-managed - // config, sandbox policy, …) never holds the handle indefinitely. - // Fall through to the fingerprint on timeout. - { encoding: 'utf8', timeout: 500 } - ) + const stdout = await readKeyboardInputSourceId() const trimmed = stdout.trim() return trimmed.length > 0 ? trimmed : null } catch {