Skip to content

Cold <webview> navigation stalls an unrelated window on macOS with GPU acceleration enabled #56005

Open

Description

@Anton-Horn

Preflight Checklist

  • Reviewed the contributing guidelines and code of conduct.
  • Searched the Electron issue tracker for a matching report.

Electron Version

Electron 45.4.1 (Chromium 156.0.8078.100) and Electron 47.0.0-nightly.20261120 (Chromium 160.0.8168.0).

What operating system(s) are you using?

macOS

Operating System Version

macOS 27.2.1 (26B131)

What arch are you using?

arm64 (including Apple Silicon), Apple M5

Last Known Working Electron version

Unknown

Does the issue also appear in Chromium / Google Chrome?

I don't know how to test

Expected Behavior

The canvas continues presenting frames while the webview prepares its first frame.

Actual Behavior

On Electron 45.4.1, the worst cold pan gap was 1.37 s with the webview embedded and 1.36 s with the webview in a separate window. The settled gap was about 9 ms. Electron 47 nightly also reproduced the embedded case, with a 1.59 s cold gap and a 9.3 ms settled gap.

Testcase Gist URL

The standalone testcase source and run commands are included in Additional Information.

Additional Information

  1. Launch stock Electron with a fresh test profile and GPU cache. The repro runs with hidden windows and uses a local page with gradients, shadows, and filters.
  2. Pan a canvas using trusted Chromium wheel input while the native <webview> loads the fixture. Repeat with the webview in a separate hidden BrowserWindow in the same Electron instance.
  3. Compare the worst canvas requestAnimationFrame gap during confirmed guest first paint with the gap after the page settles.
In-depth investigation

GPU compositing, GPU rasterization, WebGL, and Skia Graphite were active. The nightly trace shows a 564 ms GPU raster flush that used 13 ms of thread CPU time and overlapped Metal shader compilation. The separate-window control suggests the stall involves shared GPU work. The exact dependency still needs confirmation.

Save the three files below in one directory, preserving the fixtures/ subdirectory. Then run:

npm install
REPRO_GPU_MINIMAL_REPRO=1 npm run repro -- --grep 'host pan$'
REPRO_GPU_MINIMAL_REPRO=1 REPRO_GPU_SEPARATE_WINDOW=1 npm run repro -- --grep 'host pan$'

REPRO_ELECTRON_EXECUTABLE selects a different stock Electron executable. REPRO_GPU_MINIMAL_TRACE=1 records a Perfetto trace.

package.json
{
  "name": "electron-webview-cold-frame-repro",
  "private": true,
  "scripts": { "repro": "playwright test --workers=1" },
  "devDependencies": {
    "@playwright/test": "1.61.1",
    "electron": "45.4.1",
    "playwright": "1.61.1"
  }
}
fixtures/cold-electron.ts
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readdirSync } from 'node:fs'
import path from 'node:path'

/** Give Metal a fresh cache identity without clearing the user's GPU caches. */
export function copyElectronForColdGpuCache(source: string): { root: string; executablePath: string } {
  if (process.platform !== 'darwin') throw new Error('Metal cache isolation requires macOS')
  const root = mkdtempSync('/private/tmp/electron-cold-gpu-')
  const copy = path.join(root, 'Electron.app')
  execFileSync('/bin/cp', ['-cR', path.resolve(source, '../../..'), copy])
  const frameworks = path.join(copy, 'Contents/Frameworks')
  const bundles = [copy, ...readdirSync(frameworks).filter(name => name.endsWith('.app')).map(name => path.join(frameworks, name))]
  for (const bundle of bundles) {
    const plist = path.join(bundle, 'Contents/Info.plist')
    const id = execFileSync('/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', plist], { encoding: 'utf8' }).trim()
    execFileSync('/usr/libexec/PlistBuddy', ['-c', `Set :CFBundleIdentifier ${id}.${path.basename(root)}`, plist])
  }
  return { root, executablePath: path.join(copy, 'Contents/MacOS/Electron') }
}
webview-cold.spec.ts
// Standalone stock Electron reproduction.
import { test, expect } from '@playwright/test'
import { _electron as electron, type Page } from 'playwright'
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { copyElectronForColdGpuCache } from './fixtures/cold-electron'

const hostHtml = `
  <!doctype html>
  <style>
    body { margin: 0; background: #223; overflow: hidden }
    #world { position: absolute; left: 100px; top: 80px; will-change: transform }
    .card { position: absolute; left: -58px; width: 48px; height: 80px;
            background: #405a73; border-radius: 8px }
    webview { width: 900px; height: 650px }
  </style>
  <div id="world"><div class="card"></div><webview src="about:blank"></webview></div>
`

// Exercise several common first-paint paths with a fixed, local document.
const guestHtml = `
  <!doctype html>
  <meta charset="utf-8">
  <style>
    body { margin: 0; color: #f4f5f7; background: #192738; font: 14px system-ui }
    main { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; padding: 4px;
           background: linear-gradient(125deg, #0e2c57, #744727) }
    article { min-height: 29px; padding: 3px; border-radius: 7px; overflow: hidden;
              background: linear-gradient(20deg, #7661a4a8, transparent), #a2f8;
              box-shadow: inset 1px 2px 3px #fff3, 0 3px 6px #1321 }
    article:nth-child(2n) { clip-path: inset(2px 1px 1px round 4px 10px) }
    article:nth-child(3n) { filter: drop-shadow(2px 1px 2px #8debff) saturate(.8) }
    article:nth-child(4n) { background: radial-gradient(ellipse at 50% 10%, #ffc7, transparent 75%) }
    article:nth-child(5n) { backdrop-filter: blur(6px); mix-blend-mode: screen }
    article:nth-child(7n) { mask-image: linear-gradient(to left, #000, transparent) }
  </style>
  <button id="click-probe" onclick="if (event.isTrusted) this.dataset.clicked = 'yes'">Native input</button>
  <main>${Array.from({ length: 96 }, (_, i) => `<article>Build report ${i + 1}</article>`).join('')}</main>
`

async function measureGesture(page: Page, action: 'pan' | 'zoom', navigate?: () => Promise<void>) {
  const cdp = await page.context().newCDPSession(page)
  await page.locator('#world').evaluate(world => {
    (world as HTMLElement).style.transform = ''
    delete document.body.dataset.gesture
  })
  let pending = false
  let inputError: unknown
  const timer = setInterval(() => {
    if (pending || inputError) return
    pending = true
    void cdp.send('Input.dispatchMouseEvent', {
      type: 'mouseWheel', x: 16, y: 120, deltaX: action === 'pan' ? 2 : 0, deltaY: 1,
      modifiers: action === 'zoom' ? 2 : 0,
    }).catch(error => { inputError = error }).finally(() => { pending = false })
  }, 16)
  try {
    const measurement = page.evaluate(async ({ action }) => {
      const world = document.querySelector<HTMLElement>('#world')!
      const gaps: number[] = []
      let wheelEvents = 0
      const onWheel = (event: WheelEvent) => {
        if (!event.isTrusted) return
        event.preventDefault()
        if (wheelEvents++ === 0) document.body.dataset.gesture = 'active'
        const phase = Math.sin(wheelEvents / 30)
        world.style.transform = action === 'pan'
          ? `translate3d(${phase * 40}px, 0, 0)`
          : `scale(${1 + phase * .15})`
      }
      document.addEventListener('wheel', onWheel, { passive: false })
      const started = performance.now()
      performance.mark('browser-load-gesture-start')
      let previous = started, raf = 0
      const frame = (now: number) => {
        const gapMs = now - previous
        gaps.push(gapMs)
        if (gapMs > 25) performance.measure('browser-load-slow-frame', { start: previous, end: now })
        previous = now
        raf = requestAnimationFrame(frame)
      }
      raf = requestAnimationFrame(frame)
      await new Promise(resolve => setTimeout(resolve, 4000))
      cancelAnimationFrame(raf)
      document.removeEventListener('wheel', onWheel)
      gaps.sort((a, b) => a - b)
      return {
        wheelEvents, p95Ms: gaps[Math.floor(gaps.length * .95)], maxMs: gaps.at(-1) ?? 0,
        startedAt: performance.timeOrigin + started, endedAt: performance.timeOrigin + performance.now(),
      }
    }, { action })
    const startNavigation = (async () => {
      if (!navigate) return
      await page.waitForFunction(() => document.body.dataset.gesture === 'active', undefined, { timeout: 3500 })
      await navigate()
    })()
    const [result] = await Promise.all([measurement, startNavigation])
    if (inputError) throw inputError
    expect(result.wheelEvents, 'Chromium delivered trusted gesture input').toBeGreaterThan(0)
    return result
  } finally {
    clearInterval(timer)
    await cdp.detach()
  }
}

for (const action of ['pan', 'zoom'] as const) {
  test(`cold guest GPU work versus Electron host ${action}`, async () => {
    test.skip(process.env.REPRO_GPU_MINIMAL_REPRO !== '1', 'Opt-in isolated cold GPU reproduction')
    test.setTimeout(90_000)
    const testInfo = test.info()
    const scratch = mkdtempSync(path.join(os.tmpdir(), 'electron-webview-repro-'))
    let coldBundle: ReturnType<typeof copyElectronForColdGpuCache> | undefined
    let app: Awaited<ReturnType<typeof electron.launch>> | undefined
    try {
      const source = process.env.REPRO_ELECTRON_EXECUTABLE ?? require('electron') as string
      // macOS also caches Metal pipelines outside Electron's temporary profile.
      if (process.platform === 'darwin') coldBundle = copyElectronForColdGpuCache(source)
      const entry = path.join(scratch, 'main.cjs')
      const separate = process.env.REPRO_GPU_SEPARATE_WINDOW === '1'
      const webviewTag = '<webview src="about:blank"></webview>'
      writeFileSync(path.join(scratch, 'host.html'), separate ? hostHtml.replace(webviewTag, '') : hostHtml)
      if (separate) writeFileSync(path.join(scratch, 'guest-host.html'), hostHtml)
      writeFileSync(path.join(scratch, 'guest.html'), guestHtml)
      writeFileSync(entry, `
        const { app, BrowserWindow } = require('electron')
        const path = require('node:path')
        app.setPath('userData', path.join(__dirname, 'profile'))
        app.commandLine.appendSwitch('deadline-to-synchronize-surfaces', '0')
        const windows = []
        app.whenReady().then(async () => {
          app.dock?.hide()
          const options = {
            show: false, width: 1400, height: 950,
            webPreferences: { webviewTag: true, backgroundThrottling: false },
          }
          const host = new BrowserWindow(options)
          windows.push(host)
          await host.loadFile(path.join(__dirname, 'host.html'))
          if (${separate}) {
            const guestHost = new BrowserWindow(options)
            windows.push(guestHost)
            await guestHost.loadFile(path.join(__dirname, 'guest-host.html'))
          }
        })
      `)
      app = await electron.launch({ executablePath: coldBundle?.executablePath ?? source, args: [entry] })
      const page = await app.firstWindow()
      const engine = app
      const findGuestId = () => engine.evaluate(({ webContents }) =>
        webContents.getAllWebContents().find(contents => contents.getType() === 'webview')?.id ?? 0,
      )
      await expect.poll(findGuestId, { message: 'The native webview attached' }).toBeGreaterThan(0)
      const guestId = await findGuestId()
      const url = pathToFileURL(path.join(scratch, 'guest.html')).href
      const tracePath = testInfo.outputPath('cold.pftrace')
      const trace = process.env.REPRO_GPU_MINIMAL_TRACE === '1'
      if (trace) await engine.evaluate(({ contentTracing }) => contentTracing.startRecording({
        included_categories: ['cc', 'gpu', 'viz', 'input', 'blink.user_timing', 'skia', 'toplevel',
          'disabled-by-default-skia.gpu', 'disabled-by-default-gpu.dawn',
          'disabled-by-default-gpu.graphite.dawn', 'gpu.dawn', 'gpu.dawn.gpu_work'],
      }))
      let cold: Awaited<ReturnType<typeof measureGesture>>
      try {
        cold = await measureGesture(page, action, () => engine.evaluate(({ webContents }, { id, url }) => {
          void webContents.fromId(id)!.loadURL(url).catch(() => {})
        }, { id: guestId, url }))
      } finally {
        if (trace) await engine.evaluate(({ contentTracing }, destination) => contentTracing.stopRecording(destination), tracePath)
      }
      const paint = await engine.evaluate(({ webContents }, id) => webContents.fromId(id)!.executeJavaScript(`
        (() => {
          const firstPaint = performance.getEntriesByName('first-contentful-paint')[0]
          return firstPaint ? { at: performance.timeOrigin + firstPaint.startTime, ms: firstPaint.startTime } : null
        })()
      `) as Promise<{ at: number; ms: number } | null>, guestId)
      expect(paint, 'The webview painted the fixture').not.toBeNull()
      expect(paint!.at, 'The fixture painted during the gesture').toBeGreaterThanOrEqual(cold.startedAt)
      expect(paint!.at, 'The fixture painted during the gesture').toBeLessThanOrEqual(cold.endedAt)
      const gpu = await engine.evaluate(({ app }) => app.getGPUFeatureStatus())
      const settled = await measureGesture(page, action)
      await page.locator('#world').evaluate(world => { (world as HTMLElement).style.transform = '' })
      const pixelCheck = await engine.evaluate(async ({ webContents }, id) => {
        const image = await webContents.fromId(id)!.capturePage()
        const pixels = image.toBitmap()
        const colors = new Set<number>()
        for (let offset = 0; offset + 4 <= pixels.length; offset += 256) {
          colors.add(pixels.readUInt32LE(offset))
        }
        const sha256 = process.getBuiltinModule('node:crypto')!.createHash('sha256').update(pixels).digest('hex')
        return { ...image.getSize(), sampledColors: colors.size, sha256 }
      }, guestId)
      expect(pixelCheck.sampledColors, 'The rendered guest contains the fixture artwork').toBeGreaterThan(5)
      const browserPage = separate
        ? engine.windows().find(candidate => candidate.url().endsWith('/guest-host.html'))
        : page
      expect(browserPage, 'The hidden window hosting the webview attached').toBeDefined()
      const guestBounds = await browserPage!.locator('webview').boundingBox()
      expect(guestBounds).not.toBeNull()
      const buttonCenter = await engine.evaluate(({ webContents }, id) => webContents.fromId(id)!.executeJavaScript(`
        (() => {
          const {x, y, width, height} = document.querySelector('#click-probe').getBoundingClientRect()
          return {x: x + width / 2, y: y + height / 2}
        })()
      `) as Promise<{ x: number; y: number }>, guestId)
      await browserPage!.mouse.click(guestBounds!.x + buttonCenter.x, guestBounds!.y + buttonCenter.y)
      await expect.poll(() => engine.evaluate(({ webContents }, id) => webContents.fromId(id)!.executeJavaScript(
        "document.querySelector('#click-probe').dataset.clicked",
      ), guestId), { message: 'A trusted click reached the native webview' }).toBe('yes')
      const versions = await engine.evaluate(() => ({ electron: process.versions.electron, chromium: process.versions.chrome }))
      const result = { action, versions, separate, cold, settled, firstContentfulPaintMs: paint!.ms, gpu, pixelCheck }
      console.log('MINIMAL_GPU_REPRO', JSON.stringify(result))
      writeFileSync(testInfo.outputPath(`minimal-${action}.json`), JSON.stringify(result, null, 2))
      if (process.env.REPRO_GPU_MINIMAL_ASSERT_SMOOTH === '1') {
        expect(cold.p95Ms).toBeLessThan(16.7)
        expect(cold.maxMs).toBeLessThan(25)
      }
    } finally {
      try { await app?.close() } finally {
        if (coldBundle) rmSync(coldBundle.root, { recursive: true, force: true })
        rmSync(scratch, { recursive: true, force: true })
      }
    }
  })
}

Activity

  1. github-actions commented on Nov 22, 2026

    @github-actions
    Contributor

    Hello @Anton-Horn. Thanks for taking the time to open an issue and helping to make Electron better!

    This issue was automatically closed because its body does not follow any of this repository's issue templates. Maintainers rely on the sections in those templates to triage issues, and issues that are missing them usually cannot be acted upon.

    To get this issue triaged, please either:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions