Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/renderer/src/lib/keyboard-layout/korean-input-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,41 @@ describe('prefetchKoreanInputSource', () => {
await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(2))
})
})

describe('cold-start probe', () => {
beforeEach(() => {
_resetKoreanInputSourceForTests()
})

it('does not cache a null read as a confirmed non-Korean source', async () => {
// Why: on m4air a fresh session sent ₩ for the first presses — the startup
// read returned null (IPC not exposed yet) and was cached as "not Korean".
const win = makeMockWindow()
let call = 0
const reader = async (): Promise<string | null> => {
call += 1
return call === 1 ? null : 'com.apple.inputmethod.Korean.2SetKorean'
}

prefetchKoreanInputSource({ win, readInputSourceId: reader })
await vi.waitFor(() => expect(isKoreanInputSourceActive()).toBe(true))
expect(call).toBeGreaterThan(1)
})

it('gives up after a bounded number of probes when the reader never reports', async () => {
const win = makeMockWindow()
let call = 0
const reader = async (): Promise<string | null> => {
call += 1
return null
}

prefetchKoreanInputSource({ win, readInputSourceId: reader })
await vi.waitFor(() => expect(call).toBeGreaterThanOrEqual(4), { timeout: 5000 })
await new Promise((resolve) => setTimeout(resolve, 300))
// Each probe spawns four processes; an unbounded retry would be worse than
// the cold gate it fixes.
expect(call).toBeLessThanOrEqual(4)
expect(isKoreanInputSourceActive()).toBe(false)
})
})
41 changes: 40 additions & 1 deletion src/renderer/src/lib/keyboard-layout/korean-input-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ const INPUT_TOGGLE_KEY_CODES: ReadonlySet<string> = new Set(['CapsLock', 'Lang1'

const KEYBOARD_ACTIVITY_REFRESH_COOLDOWN_MS = 2000

/** Bounded so a host that never reports an input source costs four probes, not
* one per keystroke — each probe spawns `defaults export | plutil | plutil`. */
const INITIAL_PROBE_BACKOFF_MS: readonly number[] = [50, 200, 750]

export function isKoreanInputSourceId(id: string | null | undefined): boolean {
if (!id) {
return false
Expand Down Expand Up @@ -101,6 +105,13 @@ async function refreshInputSourceId(readInputSourceId: InputSourceIdReader): Pro
// misclassify the active input source until the next refresh.
return
}
if (id === null) {
// Why: the reader returns null for "no signal" (IPC not yet exposed at
// startup, transient rejection) as well as for a genuinely absent source.
// Caching that as false turns an unknown into a confirmed negative, which
// is what left the gate cold for the first keystrokes of a session.
return
}
cachedIsKorean = isKoreanInputSourceId(id)
}

Expand Down Expand Up @@ -147,7 +158,35 @@ export function prefetchKoreanInputSource(options: PrefetchKoreanInputSourceOpti
// both keydown and keyup so a held toggle key still refreshes on release.
target.addEventListener('keydown', keyboardActivityCallback, true)
target.addEventListener('keyup', keyboardActivityCallback, true)
requestRefresh(readInputSourceId, true)
void runInitialProbe(readInputSourceId, target)
}

/** Why: a keystroke-triggered refresh is async, so it can never classify the
* press that triggered it — the cache has to be warm BEFORE the first key. At
* startup the IPC is not always exposed yet, so retry with backoff until the
* reader yields an ID rather than leaving the gate cold for the session. */
async function runInitialProbe(
readInputSourceId: InputSourceIdReader,
target: Pick<Window, 'addEventListener' | 'removeEventListener'>
): Promise<void> {
for (const delayMs of INITIAL_PROBE_BACKOFF_MS) {
// Why: a reset (or a prefetch onto another window) must stop this loop, or
// it repopulates the cache the reset just cleared.
if (!listenerAttached || focusTarget !== target) {
return
}
lastRefreshAt = Date.now()
await refreshInputSourceId(readInputSourceId)
if (cachedIsKorean !== null) {
return
}
await new Promise((resolve) => setTimeout(resolve, delayMs))
}
if (!listenerAttached || focusTarget !== target) {
return
}
lastRefreshAt = Date.now()
await refreshInputSourceId(readInputSourceId)
Comment on lines +161 to +189

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Bind each startup probe to a listener session.

A reset followed by prefetchKoreanInputSource() on the same Window does not stop the old loop. Lines 175 and 185 pass again after the new listener sets listenerAttached and restores the same focusTarget.

The old loop can then call its old readInputSourceId and overwrite the new cache value. Add a monotonically increasing listener-session token. Capture it in prefetchKoreanInputSource(). Check it before every probe. Increment it during reset. Add a regression test that resets and re-prefetches the same mock window with a different reader.

The PR objective requires retries to stop on reset.

}

/** Strict gate: only true when the active macOS input source is known to be a
Expand Down
Loading