Skip to content

test(terminal): pin IME chord survival across mid-composition re-renders - #12357

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/sta-3291-churn-canary
Aug 4, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/sta-3291-churn-canary

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an IME regression test pinning the STA-3291 failure mode behaviorally. The terminal keyboard effect owns the tab's IME chord state; before #12348 it tore down and re-registered on every TerminalPane render, so any render landing mid-composition silently reset that state. #12348 fixed the cause and pinned listener-registration stability; this test pins the user-visible consequence, so a future regression fails on behavior rather than on an internal counter.

The test wires the hook TerminalPane-shaped (dependency objects rebuilt every render) and interleaves re-renders through modifier hold, composition start, and five auto-repeat Process/229 keydowns. It asserts the bare Enter redispatch is still absorbed and that no newline is sent.

Verified non-vacuous: wired through the pre-fix (unmemoized) factory, the redispatch is not absorbed and the test fails.

Also verified on real Windows hardware with the genuine MS Korean 2-Set IME — see the comment below for the raw per-keystroke PTY capture. Five Shift-held double consonants (ㅃㅉㄸㄲㅆ) plus a composed syllable produced exactly one 0d, from the deliberate Enter, with zero listener churn.

Screenshots

No visual change.

Testing

  • pnpm typecheck — web project, clean tsbuildinfo, exit 0
  • pnpm test — targeted: the IME suites, keyboard-handlers, and both expand-collapse suites — 43/43 pass on current main
  • pnpm lint — oxlint + react-doctor + oxfmt via pre-commit, clean
  • pnpm build — not run (test-only change; no production code touched)
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

AI Review Report

Reviewed for vacuity (confirmed the test fails against pre-fix wiring), for whether the assertion is behavioral rather than structural (it asserts absorbed redispatch and zero newline sends, not listener counts), and for platform assumptions. Cross-platform: the test forces the Windows IME code path via a userAgent stub, which is how the neighboring IME suites already work; no production code, shortcuts, labels, paths, or shell behavior are touched, so macOS/Linux/Windows behavior is unchanged.

Security Audit

Test-only change. No input handling, command execution, path handling, auth, secrets, dependency, or IPC surface is touched. No new attack surface.

Notes

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added a development-only canary that tracks keyboard-effect registrations by tab and mounted instance. The canary prunes old history and rate-limits warnings about repeated listener registration and IME state resets. Keyboard handlers now record registrations with stable instance IDs. Tests cover thresholds, warning content, cooldowns, remounts, tab history, cleanup, IME composition, and repeated rerenders.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is complete, but it conflicts with the changes and objectives by stating that the churn canary was dropped while canary files were added. Align the description and objectives with the actual diff, and state whether the churn canary is included or removed.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the IME regression test, which is a substantive change in the pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/keyboard-effect-churn-canary.ts (1)

1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the module comment.

This comment explains implementation details across nine lines. Keep only the non-obvious reason for the canary.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 426fc25b-6d97-4e0c-924c-8b54f0fa41a4

📥 Commits

Reviewing files that changed from the base of the PR and between 25213ec and 369d016.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/expand-collapse-render-stability.test.ts
  • src/renderer/src/components/terminal-pane/keyboard-effect-churn-canary.test.ts
  • src/renderer/src/components/terminal-pane/keyboard-effect-churn-canary.ts
  • src/renderer/src/components/terminal-pane/keyboard-handlers.ts

Comment on lines +135 to +160
it('warns in dev when a dep churns, so a reintroduced regression is not silent', () => {
resetKeyboardEffectChurnCanaryForTesting()
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { scope, fields, stableDeps } = createKeyboardWiring()

const hook = renderHook(() => {
useTerminalKeyboardShortcuts({
...stableDeps,
setExpandedPane: fields.setExpandedPaneId,
restoreExpandedLayout: () => {},
refreshPaneSizes: () => {},
persistLayoutSnapshot: fields.persistLayoutSnapshot,
toggleExpandPane: () => {}
} as KeyboardHandlersDeps)
})

for (let render = 0; render < 10; render++) {
hook.rerender()
}

expect(warnSpy).toHaveBeenCalledTimes(1)
expect(String(warnSpy.mock.calls[0]?.[0])).toContain('tab-1')
hook.unmount()
scope.remove()
resetKeyboardEffectChurnCanaryForTesting()
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Run test cleanup when assertions fail.

If either assertion fails, this test leaves window listeners, the DOM scope, the canary state, and the console.warn spy installed. Use try/finally or afterEach cleanup so a regression does not contaminate later tests.

@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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: af23c927-de98-40f6-8a33-4c04f338b929

📥 Commits

Reviewing files that changed from the base of the PR and between 369d016 and 028d209.

📒 Files selected for processing (1)
  • src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx

Comment on lines +385 to +393
const hook = renderHook(() => {
const actions = useExpandCollapseActions({ ...factoryFields, tabId: 'tab-1' })
useTerminalKeyboardShortcuts({
...harness.deps,
setExpandedPane: actions.setExpandedPane,
restoreExpandedLayout: actions.restoreExpandedLayout,
refreshPaneSizes: actions.refreshPaneSizes,
toggleExpandPane: actions.toggleExpandPane
})

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/sh
set -eu

ast-grep outline src/renderer/src/components/terminal-pane/keyboard-handlers.ts \
  --match useTerminalKeyboardShortcuts --view expanded

rg -n -C 6 \
  'useEffect\(|setExpandedPane|restoreExpandedLayout|refreshPaneSizes|toggleExpandPane' \
  src/renderer/src/components/terminal-pane/keyboard-handlers.ts

sed -n '369,438p' \
  src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx

Repository: stablyai/orca

Length of output: 6224


🏁 Script executed:

#!/bin/sh
set -eu

echo "## useTermKeyboardShortcuts outline"
ast-grep outline src/renderer/src/components/terminal-pane/keyboard-handlers.ts \
  --match useTerminalKeyboardShortcuts --view expanded || true

echo "## keyboard-handlers relevant sections"
sed -n '238,310p' src/renderer/src/components/terminal-pane/keyboard-handlers.ts
sed -n '900,985p' src/renderer/src/components/terminal-pane/keyboard-handlers.ts

echo "## Locate useExpandCollapseActions"
rg -n "function useExpandCollapseActions|export function useExpandCollapseActions|const useExpandCollapseActions|useExpandCollapseActions" src/renderer/src/components/terminal-pane -C 4

echo "## Related tests around ime test"
rg -n "rerender\(|persistLayoutSnapshot|pendingPaneSizeRefreshFrameIdsRef|expandCollapse" src/renderer/src/components/terminal-pane/keyboard-handlers-ime.test.tsx -C 3

Repository: stablyai/orca

Length of output: 16847


🏁 Script executed:

#!/bin/sh
set -eu

echo "## expand-collapse hook implementation"
sed -n '200,285p' src/renderer/src/components/terminal-pane/expand-collapse.ts

echo "## existing render-stability test"
sed -n '33,63p' src/renderer/src/components/terminal-pane/expand-collapse-render-stability.test.ts

echo "## deterministic hook dependency check"
python3 - <<'PY'
from pathlib import Path
import re

expand = Path("src/renderer/src/components/terminal-pane/expand-collapse.ts").read_text()
m = re.search(r"export function useExpandCollapseActions\(state: ExpandCollapseState\)\s*\{(?P<body>.*?)\n\}\n\nexport function create", expand, re.S)
if not m:
    m = re.search(r"export function useExpandCollapseActions\(state: ExpandCollapseState\)\s*\{(?P<body>.*?)\n\}\n\n", expand, re.S)
print("found hook:", m is not None)
if m:
    body = m.group("body")
    for name in ["setExpandedPane", "restoreExpandedLayout", "refreshPaneSizes", "toggleExpandPane", "persistLayoutSnapshot"]:
        print(name, "memorized:", f"key={name}" in body or name + "=useCallback" in body or "useCallback(" + name in body or ("useCallback" in body and name + "}" in body))
print(body)
PY

Repository: stablyai/orca

Length of output: 2652


Make persistLayoutSnapshot change on each rerender.

useExpandCollapseActions memoizes the action callbacks from expand-collapse.ts, so { ...factoryFields, tabId: 'tab-1' } rebuilds the state object without changing any callback identities. useTerminalKeyboardShortcuts depends on those callbacks, so it re-registers its keyboard listeners only when one changes. Move persistLayoutSnapshot out of the repeated factory fields and create a new mock per render so the IME redirect path is exercised.

Proposed test adjustment
     const factoryFields = {
       expandedPaneIdRef: { current: null },
       expandedStyleSnapshotRef: { current: new Map() },
       containerRef: { current: null },
       managerRef: { current: null },
       setExpandedPaneId: vi.fn(),
       setTabPaneExpanded: vi.fn(),
-      pendingPaneSizeRefreshFrameIdsRef: { current: [] },
-      persistLayoutSnapshot: vi.fn()
+      pendingPaneSizeRefreshFrameIdsRef: { current: [] }
     }
     const hook = renderHook(() => {
-      const actions = useExpandCollapseActions({ ...factoryFields, tabId: 'tab-1' })
+      const actions = useExpandCollapseActions({
+        ...factoryFields,
+        tabId: 'tab-1',
+        persistLayoutSnapshot: vi.fn()
+      })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const hook = renderHook(() => {
const actions = useExpandCollapseActions({ ...factoryFields, tabId: 'tab-1' })
useTerminalKeyboardShortcuts({
...harness.deps,
setExpandedPane: actions.setExpandedPane,
restoreExpandedLayout: actions.restoreExpandedLayout,
refreshPaneSizes: actions.refreshPaneSizes,
toggleExpandPane: actions.toggleExpandPane
})
const hook = renderHook(() => {
const actions = useExpandCollapseActions({
...factoryFields,
tabId: 'tab-1',
persistLayoutSnapshot: vi.fn()
})
useTerminalKeyboardShortcuts({
...harness.deps,
setExpandedPane: actions.setExpandedPane,
restoreExpandedLayout: actions.restoreExpandedLayout,
refreshPaneSizes: actions.refreshPaneSizes,
toggleExpandPane: actions.toggleExpandPane
})

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows real-IME verification — PASS.

Ran on a Windows host against a QA worktree off current `main` (fix present at `637c7e94c9`), driving the real MS Korean 2-Set IME through the OS input stack (not synthesized DOM events), with the pane going through a real PTY.

Renderer keylog confirms genuine IME events reached the handler: HangulMode keyup, then Shift held, then a Process/keyCode-229 keydown per consonant with isComposing: true, shiftKey: true.

Raw-mode PTY capture (per keystroke, hex + ms):

52748 e38583   ㅃ   } all five typed with Shift HELD
52961 e38589   ㅉ   } (the STA-3128 double-consonant shape)
53177 e384b8   ㄸ
53393 e384b2   ㄲ
53928 e38586   ㅆ
54759 eab080   가   composed syllable
54759 0d       CR   <- the single deliberate Enter

Zero spurious newlines across the held-modifier composition; exactly one 0d, from the deliberate Enter. The decisive case is the commit itself: the IME fired Process(229) at t=615629 and Windows redispatched a bare Enter(13) at t=615631 — 2 ms apart, the classic double-Enter shape — and the PTY still received exactly one CR.

Keyboard-effect listener churn during the entire run: 0 (keyup/keypress/beforeinput/blur registrations all zero). The dev churn canary in this PR stayed silent, i.e. no false positives under real IME input.

Note for anyone reproducing: use setRawMode(true) for the stdin probe. A first attempt with a line-buffered probe showed an apparent extra newline after the first consonant, which turned out to be conhost line-editing at a Terminate batch job (Y/N)? prompt — not app behavior. Raw mode disambiguates.

QA worktree and all temp artifacts removed from the host.

…ers (STA-3291)

Busy panes render mid-composition (title updates drive renders), and the
modified-Enter chord owner must survive those renders or held-modifier
CJK input leaks newlines. Wires the hook TerminalPane-shaped (dep objects
rebuilt per render) and interleaves re-renders through hold, composition,
and auto-repeat; fails under pre-fix churn wiring (verified: redispatch
not absorbed), passes with memoized actions.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-3291-churn-canary branch from 028d209 to 90f0336 Compare August 4, 2026 19:48
@brennanb2025 brennanb2025 changed the title fix(terminal): warn in dev when keyboard effect re-registers rapidly test(terminal): pin IME chord survival across mid-composition re-renders Aug 4, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Scope reduced: the dev-only churn canary has been dropped from this PR, leaving only the IME regression test.

Reasoning: the canary's detection path required a developer to notice a console.warn. In practice nobody has DevTools open for a warning they aren't looking for, so the insurance would rarely have paid out — while permanently adding a runtime concept that every future reader of the keyboard effect has to understand.

The coverage it was meant to provide is better served by the CI regression test already merged in #12348 (which blocks a merge rather than relying on someone watching), and, if we ever want the stronger guarantee, by a test that mounts the real TerminalPane and asserts listener registration count — that would catch newly-added unstable dependencies automatically. That is deliberately not in this PR; it needs the store, PTY transports, and xterm stood up, and should be weighed on its own merits.

The Windows real-IME verification in the comment above still stands: it exercised the shipped fix and this test's exact scenario.

@brennanb2025
brennanb2025 merged commit 1816d3e into main Aug 4, 2026
42 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ers (STA-3291) (stablyai#12357)

Busy panes render mid-composition (title updates drive renders), and the
modified-Enter chord owner must survive those renders or held-modifier
CJK input leaks newlines. Wires the hook TerminalPane-shaped (dep objects
rebuilt per render) and interleaves re-renders through hold, composition,
and auto-repeat; fails under pre-fix churn wiring (verified: redispatch
not absorbed), passes with memoized actions.
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.

1 participant