From 0379df324e20e098e26339c8a71f68b6b842ee2f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 16:42:40 -0800 Subject: [PATCH 1/3] test(desktop): instrument the Escape-on-Leave-dialog step (temporary) --- apps/desktop/e2e/browser-page-dialogs.spec.ts | 104 ++++++++++++++---- 1 file changed, 85 insertions(+), 19 deletions(-) diff --git a/apps/desktop/e2e/browser-page-dialogs.spec.ts b/apps/desktop/e2e/browser-page-dialogs.spec.ts index 58582581496..3a19b9c8447 100644 --- a/apps/desktop/e2e/browser-page-dialogs.spec.ts +++ b/apps/desktop/e2e/browser-page-dialogs.spec.ts @@ -51,6 +51,16 @@ import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, ' import { BrowserPageDialogModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-dialog.tsx'))}; import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; +const diag = (globalThis.escapeDiag = []); +const stamp = (what, extra) => diag.push({ what, t: Math.round(performance.now()), active: document.activeElement?.textContent?.slice(0, 20) ?? null, hasFocus: document.hasFocus(), ...extra }); +const origAdd = window.addEventListener.bind(window); +const origRemove = window.removeEventListener.bind(window); +window.addEventListener = (type, fn, opts) => { if (type === 'keydown' && opts === true) stamp('lock-on'); return origAdd(type, fn, opts) }; +window.removeEventListener = (type, fn, opts) => { if (type === 'keydown' && opts === true) stamp('lock-off'); return origRemove(type, fn, opts) }; +origAdd('keydown', (e) => { if (e.key === 'Escape') stamp('esc-window-capture') }, true); +document.addEventListener('keydown', (e) => { if (e.key === 'Escape') stamp('esc-document-capture') }, true); +document.addEventListener('keydown', (e) => { if (e.key === 'Escape') stamp('esc-document-bubble', { prevented: e.defaultPrevented }) }); +document.addEventListener('focusin', () => stamp('focusin'), true); const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); store.subscribe(state => { @@ -288,26 +298,82 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, }) await test.step('Escape keeps the draft and returns typing to the page', async () => { - await userInput(app, form, '#draft') - // The click is queued input: reloading before the page takes focus lets that focus land - // after the modal's, leaving the Sim window without keyboard focus. - await expect.poll(() => focusedPageUrl(app)).toBe(form) - await act({ action: 'reload' }) - await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() - const shown = await pageDialog() - await shell.keyboard.press('Escape') - await expect - .poll(pageDialog, { - message: `dialog ${shown?.requestId} was showing when Escape was pressed`, + const results: unknown[] = [] + await app.evaluate(({ webContents }, url) => { + const g = globalThis as unknown as { mainEsc: unknown[] } + g.mainEsc = [] + for (const contents of webContents.getAllWebContents()) { + contents.on('before-input-event', (_event, input) => { + if (input.key === 'Escape') + g.mainEsc.push({ + url: contents.getURL().slice(0, 40), + type: input.type, + loading: contents.isLoadingMainFrame(), + t: Date.now(), + }) + }) + } + void url + }, form) + for (let attempt = 0; attempt < 8; attempt++) { + await shell.evaluate(() => { + ;(globalThis as unknown as { escapeDiag: unknown[] }).escapeDiag.length = 0 + }) + await userInput(app, form, '#draft') + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await act({ action: 'reload' }) + await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() + const shown = await pageDialog() + const before = await app.evaluate(({ webContents, BrowserWindow }, url) => { + const page = webContents.getAllWebContents().find((c) => c.getURL() === url) + ;(globalThis as unknown as { mainEsc: unknown[] }).mainEsc.length = 0 + return { + focusedContents: webContents.getFocusedWebContents()?.getURL()?.slice(0, 40) ?? null, + focusedWindow: Boolean(BrowserWindow.getFocusedWindow()), + pageLoading: page?.isLoading(), + pageLoadingMain: page?.isLoadingMainFrame(), + t: Date.now(), + } + }, form) + await shell.evaluate(() => { + ;(globalThis as unknown as { escapeDiag: { what: string }[] }).escapeDiag.push({ + what: 'pre-press', + } as never) }) - .toBeNull() - await expect.poll(() => focusedPageUrl(app)).toBe(form) - await app.evaluate(({ webContents }) => { - const contents = webContents.getFocusedWebContents() - if (!contents) throw new Error('Missing focused page') - contents.sendInputEvent({ type: 'char', keyCode: 'x' }) - }) - await expect.poll(() => draft()).toBe('xdraft') + await shell.keyboard.press('Escape') + let cleared = true + try { + await expect.poll(pageDialog, { timeout: 5000 }).toBeNull() + } catch { + cleared = false + } + const after = await pageDialog() + const renderer = await shell.evaluate( + () => (globalThis as unknown as { escapeDiag: unknown[] }).escapeDiag + ) + const main = await app.evaluate( + () => (globalThis as unknown as { mainEsc: unknown[] }).mainEsc + ) + results.push({ + attempt, + cleared, + shown: shown?.requestId, + after: after?.requestId ?? null, + before, + renderer, + main, + }) + if (!cleared) { + await shell.getByRole('button', { name: 'Stay', exact: true }).click() + await expect.poll(pageDialog).toBeNull() + } + await expect.poll(() => focusedPageUrl(app)).toBe(form) + } + console.log(`ESCAPE_DIAG ${JSON.stringify(results)}`) + const { writeFileSync, mkdirSync } = await import('node:fs') + mkdirSync('test-results', { recursive: true }) + writeFileSync('test-results/escape-diag.json', JSON.stringify(results, null, 2)) + expect(results.filter((r) => !(r as { cleared: boolean }).cleared)).toEqual([]) }) await test.step('Leave lets the navigation through without asking again', async () => { From 99f310da60bd025aebfe79ebc26c742ca7371cfe Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 16:49:34 -0800 Subject: [PATCH 2/3] fix(emcn): a modal over a native surface accepts keys as soon as focus lands --- apps/desktop/e2e/browser-page-dialogs.spec.ts | 2 +- .../emcn/src/components/modal/modal.test.tsx | 12 ++++-- packages/emcn/src/components/modal/modal.tsx | 37 +++++++++++++++---- 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/apps/desktop/e2e/browser-page-dialogs.spec.ts b/apps/desktop/e2e/browser-page-dialogs.spec.ts index 3a19b9c8447..7381e4d03ce 100644 --- a/apps/desktop/e2e/browser-page-dialogs.spec.ts +++ b/apps/desktop/e2e/browser-page-dialogs.spec.ts @@ -315,7 +315,7 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, } void url }, form) - for (let attempt = 0; attempt < 8; attempt++) { + for (let attempt = 0; attempt < 12; attempt++) { await shell.evaluate(() => { ;(globalThis as unknown as { escapeDiag: unknown[] }).escapeDiag.length = 0 }) diff --git a/packages/emcn/src/components/modal/modal.test.tsx b/packages/emcn/src/components/modal/modal.test.tsx index 5d80c85c408..5bcd7560b37 100644 --- a/packages/emcn/src/components/modal/modal.test.tsx +++ b/packages/emcn/src/components/modal/modal.test.tsx @@ -153,9 +153,15 @@ describe('native-surface modal preparation', () => { expect(readyLayers.contentLayer.className).toContain('pointer-events-none') expect(readyLayers.dialog).not.toBeNull() expect(readyLayers.dialog?.style.visibility).not.toBe('hidden') - expect(document.activeElement).toBe( - document.querySelector('[aria-label="Modal field"]') - ) + const modalField = document.querySelector('[aria-label="Modal field"]') + expect(document.activeElement).toBe(modalField) + // The control that now holds focus takes the very next key; no frame has to pass first. + const modalKeyDown = vi.fn() + modalField?.addEventListener('keydown', modalKeyDown) + const firstKey = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'x' }) + modalField?.dispatchEvent(firstKey) + expect(firstKey.defaultPrevented).toBe(false) + expect(modalKeyDown).toHaveBeenCalledOnce() }) it('fails closed when a registered preparation rejects', async () => { diff --git a/packages/emcn/src/components/modal/modal.tsx b/packages/emcn/src/components/modal/modal.tsx index 6d90ce16c0b..083a612c45e 100644 --- a/packages/emcn/src/components/modal/modal.tsx +++ b/packages/emcn/src/components/modal/modal.tsx @@ -20,6 +20,7 @@ import * as React from 'react' import * as DialogPrimitive from '@radix-ui/react-dialog' import { usePathname } from 'next/navigation' +import { flushSync } from 'react-dom' import { cn } from '../../lib/cn' import { focusFirstTextInput, focusFirstTextInputIn } from './auto-focus' @@ -79,9 +80,21 @@ export interface NativeSurfaceOcclusionPrepareDetail { interface NativeSurfaceOcclusionPreparation { completion: Promise + /** Re-enables keyboard input. Idempotent; `cancel` also releases it. */ + releaseInteraction: () => void cancel: () => void } +interface NativeSurfaceOcclusionPreparationOptions { + /** + * Keeps keyboard input blocked after preparation settles until the caller + * calls `releaseInteraction`, instead of releasing it on the next frame. A + * surface that moves focus into itself on readiness releases right after + * that focus lands, so a focused control never drops its first key. + */ + holdInteraction?: boolean +} + const PENDING_NATIVE_INTERACTION_EVENTS = [ 'beforeinput', 'compositionstart', @@ -162,7 +175,8 @@ function acquirePendingNativeInteractionLock(): () => void { * than exposing an unoccluded native surface underneath it. */ function requestNativeSurfaceOcclusionPreparation( - kind: NativeSurfaceOcclusionPrepareDetail['kind'] + kind: NativeSurfaceOcclusionPrepareDetail['kind'], + { holdInteraction = false }: NativeSurfaceOcclusionPreparationOptions = {} ): NativeSurfaceOcclusionPreparation | null { const preparations: Promise[] = [] const detail: NativeSurfaceOcclusionPrepareDetail = { @@ -178,12 +192,13 @@ function requestNativeSurfaceOcclusionPreparation( const releaseInteractionLock = acquirePendingNativeInteractionLock() let releaseFrame: number | null = null const completion = Promise.all(preparations).then(() => undefined) - // Keep keyboard input blocked through the first ready paint. The modal's - // layout effect can move focus into its real content before interaction is - // re-enabled; rejected preparation deliberately remains fail-closed until - // the owning surface unmounts and calls `cancel`. + // Keep keyboard input blocked through the first ready paint, or with + // `holdInteraction` until the caller has moved focus and releases it. + // Rejected preparation deliberately remains fail-closed until the owning + // surface unmounts and calls `cancel`. void completion.then( () => { + if (holdInteraction) return releaseFrame = requestAnimationFrame(() => { releaseFrame = null releaseInteractionLock() @@ -193,6 +208,7 @@ function requestNativeSurfaceOcclusionPreparation( ) return { completion, + releaseInteraction: releaseInteractionLock, cancel: () => { if (releaseFrame !== null) cancelAnimationFrame(releaseFrame) releaseFrame = null @@ -340,14 +356,21 @@ function NativeSurfaceModalGate({ barrierClaimedRef, onReadyChange }: NativeSurf let active = true onReadyChange(false) - const preparation = requestNativeSurfaceOcclusionPreparation('modal') + const preparation = requestNativeSurfaceOcclusionPreparation('modal', { + holdInteraction: true, + }) barrierClaimedRef.current = preparation !== null if (!preparation) { onReadyChange(true) } else { void preparation.completion.then( () => { - if (active) onReadyChange(true) + if (!active) return + // Commit readiness now so ModalContent's layout effect moves focus into + // the dialog, then accept keys: a focused control must take the very + // next key (Escape on a Leave prompt), never drop it to the barrier. + flushSync(() => onReadyChange(true)) + preparation.releaseInteraction() }, () => { // A failed native-surface transition is unsafe to reveal through. From d3155f9f4ce45c5c5d26eaa74fd53d705cf489ea Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 16:57:38 -0800 Subject: [PATCH 3/3] test(desktop): drop the Escape-step instrumentation --- apps/desktop/e2e/browser-page-dialogs.spec.ts | 104 ++++-------------- 1 file changed, 19 insertions(+), 85 deletions(-) diff --git a/apps/desktop/e2e/browser-page-dialogs.spec.ts b/apps/desktop/e2e/browser-page-dialogs.spec.ts index 7381e4d03ce..58582581496 100644 --- a/apps/desktop/e2e/browser-page-dialogs.spec.ts +++ b/apps/desktop/e2e/browser-page-dialogs.spec.ts @@ -51,16 +51,6 @@ import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, ' import { BrowserPageDialogModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-dialog.tsx'))}; import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; -const diag = (globalThis.escapeDiag = []); -const stamp = (what, extra) => diag.push({ what, t: Math.round(performance.now()), active: document.activeElement?.textContent?.slice(0, 20) ?? null, hasFocus: document.hasFocus(), ...extra }); -const origAdd = window.addEventListener.bind(window); -const origRemove = window.removeEventListener.bind(window); -window.addEventListener = (type, fn, opts) => { if (type === 'keydown' && opts === true) stamp('lock-on'); return origAdd(type, fn, opts) }; -window.removeEventListener = (type, fn, opts) => { if (type === 'keydown' && opts === true) stamp('lock-off'); return origRemove(type, fn, opts) }; -origAdd('keydown', (e) => { if (e.key === 'Escape') stamp('esc-window-capture') }, true); -document.addEventListener('keydown', (e) => { if (e.key === 'Escape') stamp('esc-document-capture') }, true); -document.addEventListener('keydown', (e) => { if (e.key === 'Escape') stamp('esc-document-bubble', { prevented: e.defaultPrevented }) }); -document.addEventListener('focusin', () => stamp('focusin'), true); const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); store.subscribe(state => { @@ -298,82 +288,26 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, }) await test.step('Escape keeps the draft and returns typing to the page', async () => { - const results: unknown[] = [] - await app.evaluate(({ webContents }, url) => { - const g = globalThis as unknown as { mainEsc: unknown[] } - g.mainEsc = [] - for (const contents of webContents.getAllWebContents()) { - contents.on('before-input-event', (_event, input) => { - if (input.key === 'Escape') - g.mainEsc.push({ - url: contents.getURL().slice(0, 40), - type: input.type, - loading: contents.isLoadingMainFrame(), - t: Date.now(), - }) - }) - } - void url - }, form) - for (let attempt = 0; attempt < 12; attempt++) { - await shell.evaluate(() => { - ;(globalThis as unknown as { escapeDiag: unknown[] }).escapeDiag.length = 0 - }) - await userInput(app, form, '#draft') - await expect.poll(() => focusedPageUrl(app)).toBe(form) - await act({ action: 'reload' }) - await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() - const shown = await pageDialog() - const before = await app.evaluate(({ webContents, BrowserWindow }, url) => { - const page = webContents.getAllWebContents().find((c) => c.getURL() === url) - ;(globalThis as unknown as { mainEsc: unknown[] }).mainEsc.length = 0 - return { - focusedContents: webContents.getFocusedWebContents()?.getURL()?.slice(0, 40) ?? null, - focusedWindow: Boolean(BrowserWindow.getFocusedWindow()), - pageLoading: page?.isLoading(), - pageLoadingMain: page?.isLoadingMainFrame(), - t: Date.now(), - } - }, form) - await shell.evaluate(() => { - ;(globalThis as unknown as { escapeDiag: { what: string }[] }).escapeDiag.push({ - what: 'pre-press', - } as never) - }) - await shell.keyboard.press('Escape') - let cleared = true - try { - await expect.poll(pageDialog, { timeout: 5000 }).toBeNull() - } catch { - cleared = false - } - const after = await pageDialog() - const renderer = await shell.evaluate( - () => (globalThis as unknown as { escapeDiag: unknown[] }).escapeDiag - ) - const main = await app.evaluate( - () => (globalThis as unknown as { mainEsc: unknown[] }).mainEsc - ) - results.push({ - attempt, - cleared, - shown: shown?.requestId, - after: after?.requestId ?? null, - before, - renderer, - main, + await userInput(app, form, '#draft') + // The click is queued input: reloading before the page takes focus lets that focus land + // after the modal's, leaving the Sim window without keyboard focus. + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await act({ action: 'reload' }) + await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() + const shown = await pageDialog() + await shell.keyboard.press('Escape') + await expect + .poll(pageDialog, { + message: `dialog ${shown?.requestId} was showing when Escape was pressed`, }) - if (!cleared) { - await shell.getByRole('button', { name: 'Stay', exact: true }).click() - await expect.poll(pageDialog).toBeNull() - } - await expect.poll(() => focusedPageUrl(app)).toBe(form) - } - console.log(`ESCAPE_DIAG ${JSON.stringify(results)}`) - const { writeFileSync, mkdirSync } = await import('node:fs') - mkdirSync('test-results', { recursive: true }) - writeFileSync('test-results/escape-diag.json', JSON.stringify(results, null, 2)) - expect(results.filter((r) => !(r as { cleared: boolean }).cleared)).toEqual([]) + .toBeNull() + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await app.evaluate(({ webContents }) => { + const contents = webContents.getFocusedWebContents() + if (!contents) throw new Error('Missing focused page') + contents.sendInputEvent({ type: 'char', keyCode: 'x' }) + }) + await expect.poll(() => draft()).toBe('xdraft') }) await test.step('Leave lets the navigation through without asking again', async () => {