Skip to content

[BUG]: Linux/Wayland: clipboard reads keep returning the app's own last-copied content and ignore later copies made by other apps #54645

Open

Description

@Loss-of-time

Preflight Checklist

Electron Version

43.7.7 (also reproduces on 40.0.0)

What operating system(s) are you using?

Other Linux

Operating System Version

CachyOS (Arch-based), KDE Plasma 6.7.5, KWin 6.7.5, Wayland session, launched with --ozone-platform=wayland (uname -a: Linux cachyos-x8664 6.x x86_64)

What arch are you using?

x64

Last Known Working Electron version

Unknown

Does the issue also appear in Chromium / Google Chrome?

I don't know how to test

Expected Behavior

After another application puts new content on the system clipboard, clipboard.readImage() / clipboard.readBuffer('image/png') should return that new content, so that pasting in the app matches what every other app sees.

Actual Behavior

If the app writes to the clipboard while no input event has been processed by the app (in my test: clipboard.writeImage() from a setTimeout 3 s after startup, without clicking the window), then every later clipboard read in that app keeps returning the app's own just-written image and ignores all subsequent copies made by other applications — for the rest of the app's lifetime. Other applications (Krita, the KDE clipboard manager history, a plain Wayland client) see the current clipboard correctly.

Reproduced with both Electron 43.7.7 (Chromium 150.0.7871.250) and Electron 40.0.0 (Chromium 144.0.7559.60). Observed in the wild with a shipped Electron app: QQ for Linux 3.2.34 (Electron 40) — after copying an image inside that app, "paste image" in that app keeps pasting that same image no matter what is copied afterwards elsewhere, until the app is restarted.

Testcase Gist URL

https://gist.github.com/Loss-of-time/80b14ca56a79341c2b132c811c618862

Additional Information

Run with npm i [email protected] && WAYLAND_DEBUG=1 npx electron --ozone-platform=wayland .; do not click the window. After ~3 s the app logs WROTE bytes=292 sha=aed04030680eec8f. Then set the clipboard to a different image from any other app:

WROTE bytes=292 sha=aed04030680eec8f
read bytes=442 sha=738b75e6c5e4af47     <- own data (re-encoded)
read bytes=442 sha=738b75e6c5e4af47     <- unchanged, while the real clipboard is now another image (685 bytes, sha 5171e045…)
In-depth investigation

ui/ozone/platform/wayland/host/wayland_clipboard.cc — Write() sets source_ (so IsSelectionOwner() becomes true) before checking whether a serial is available; when none is found it only logs a warning, so wl_data_device.set_selection is never sent:

void Write(const ui::PlatformClipboard::DataMap* data) final {
    if (!data || data->empty()) {
      offered_data_.clear();
      source_.reset();
    } else {
      offered_data_ = *data;
      source_ = manager_->CreateSource(this);          // ownership claimed locally
      source_->Offer(GetOfferedMimeTypes());
      auto serial = connection_->serial_tracker().GetSerial(
          {wl::SerialType::kTouchPress, wl::SerialType::kMousePress, wl::SerialType::kKeyPress});
      if (serial.has_value()) {
        GetDevice()->SetSelectionSource(source_.get(), serial->value);
      } else {
        LOG(WARNING) << "No serial found for selection.";   // compositor is never told
      }
    }
    ...
}

(Chromium 144 has a TODO at this exact spot: "This function should just no-op if no serial is found (ie: no recent input event has been processed yet)…"; 150's FinishWrite() has the same shape without the TODO.)

Ownership then short-circuits two more places, so the wrong belief is never corrected:

bool IsSelectionOwner() const final { return !!source_; }

void HandleNewSelectionOffer(ui::WaylandDataOfferBase* offer) const {
  if (IsSelectionOwner())
    return;                       // new selection offers are dropped, no notification
  NotifyClipboardChanged();
}

and ui/base/clipboard/clipboard_ozone.cc serves reads from the local cache while that flag is set:

  // We can use a fastpath if we are the owner of the selection.
  if (platform_clipboard_->IsSelectionOwner(buffer)) {
    auto it = offered_data_[buffer].find(mime_type);
    if (it == offered_data_[buffer].end())
      return {};
    return base::span(it->second->as_vector());
  }
  if (auto data = Read(buffer, mime_type))     // only reached when we do NOT think we own it
    return base::span(data->as_vector());

with the member documented as // Clipboard data that had been offered most recently. Used as a cache to read data if we still own it. (base::flat_map<ClipboardBuffer, PlatformClipboard::DataMap> offered_data_;)

Because set_selection was never sent, the compositor never learns about the data source and can never send wl_data_source.cancelled, so source_ is never reset and the app stays latched. In WAYLAND_DEBUG output collected during the test: create_data_source + offer("image/png") appear, set_selection appears 0 times, and after the app's own write the app receives wl_data_device.selection(wl_data_offer@…) for the new content but issues 0 wl_data_offer.receive(...) calls for it.

The same code path also causes a stale-read window when a serial is available: clicking a button in the test app (providing a serial) produces a valid set_selection; reads then generate zero wl_data_offer.receive traffic while the app believes it owns the selection, and its wl_data_source was not cancelled until 6.9 s later, when another client wrote the clipboard. In that window the app also reports its own content while other apps see the real clipboard.

Possible fixes: don't enter the "we own the selection" state when no serial is available (as the existing TODO suggests), and/or don't serve reads from offered_data_ purely because of a local ownership flag, and/or don't skip the clipboard-change notification in HandleNewSelectionOffer() while that flag is set.

Note on venue: the faulty code is in Chromium's Ozone/Wayland clipboard layer, but I could not find a way to trigger the no-serial write from Chrome web content (clipboard writes there require user activation, which provides a serial), whereas Electron's main-process clipboard.writeImage() can write with no input event at all — which is why I am filing it here.

Activity

  1. github-actions commented on Oct 5, 2026

    @github-actions
    Contributor

    Hello @Loss-of-time. 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:

  2. changed the title [-]Linux/Wayland: clipboard write without a tracked input serial latches the app onto its own clipboard cache (all later copies ignored)[/-] [+]Linux/Wayland: clipboard reads keep returning the app's own last-copied content and ignore later copies made by other apps[/+] on Oct 5, 2026
  3. changed the title [-]Linux/Wayland: clipboard reads keep returning the app's own last-copied content and ignore later copies made by other apps[/-] [+][BUG]: Linux/Wayland: clipboard reads keep returning the app's own last-copied content and ignore later copies made by other apps[/+] on Oct 5, 2026
  4. nwparker commented on Oct 6, 2026

    @nwparker

    Our Orca users are hitting it (stablyai/orca#23229). Had my AI investigate; repro below if helpful.

    Copy/paste reproduction: awaited write succeeds locally, then Electron stays on B while the system clipboard advances to C

    Tested on native Wayland: Sway 1.9 / wlroots 0.17.1, Ubuntu 24.04 x64, with Electron 44.5.1 / Chromium 152.0.7977.130 and Electron 45.0.0-alpha.15 / Chromium 156.0.8077.0. Our earlier reproduction also fails on Electron 43.7.5. This uses only Electron and wl-clipboard; no Orca code or native module.

    Needs Node/npm and wl-copy / wl-paste (wl-clipboard; e.g. sudo apt install wl-clipboard on Debian/Ubuntu). Run this in a Wayland session. Leave the new window untouched until the automatic test finishes. The test replaces your clipboard with the A/B/C text markers.

    Paste this entire block into a terminal:

    repro_dir=$(mktemp -d)
    cat > "$repro_dir/repro.cjs" <<'JS'
    const { app, BrowserWindow, clipboard } = require('electron');
    const { spawn } = require('node:child_process');
    const { mkdtempSync } = require('node:fs');
    const { join } = require('node:path');
    const { tmpdir } = require('node:os');
    
    app.setPath('userData', mkdtempSync(join(tmpdir(), 'electron-wayland-clipboard-')));
    const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
    const env = { ...process.env };
    delete env.WAYLAND_DEBUG;
    
    function command(file, args, input) {
      return new Promise((resolve, reject) => {
        // wl-copy forks an owner; avoid pipes inherited by that process.
        const child = spawn(file, args, { env, stdio: ['pipe', input === undefined ? 'pipe' : 'ignore', input === undefined ? 'pipe' : 'ignore'] });
        let output = '', error = '';
        child.stdout?.on('data', data => { output += data; });
        child.stderr?.on('data', data => { error += data; });
        child.on('error', reject);
        child.stdin.on('error', reject);
        child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`${file}: ${code}: ${error}`)));
        child.stdin.end(input);
      });
    }
    
    app.whenReady().then(async () => {
      if (process.platform !== 'linux' || !process.env.WAYLAND_DISPLAY) {
        throw new Error('Run in a native Wayland Linux session with --ozone-platform=wayland.');
      }
      const win = new BrowserWindow({ width: 820, height: 580 });
      await win.loadURL('data:text/html,' + encodeURIComponent(`
        <title>Electron Wayland clipboard reproduction</title>
        <h2>Wait for the automatic test; do not click or type yet.</h2>
        <p>This test replaces the clipboard with three harmless text markers.</p>
        <pre id="log"></pre>
        <p>After the test finishes, paste into this box with Ctrl+V:</p>
        <textarea rows="3" cols="75" autofocus></textarea>
      `));
      const log = [];
      async function print(text) {
        log.push(text);
        console.log(text);
        await win.webContents.executeJavaScript(
          'document.getElementById("log").textContent = ' + JSON.stringify(log.join('\n'))
        );
      }
      async function snapshot(label) {
        const system = await command('wl-paste', ['--no-newline']);
        const electron = await clipboard.readText();
        await print(`${label}\n  wl-paste: ${JSON.stringify(system)}\n  Electron: ${JSON.stringify(electron)}`);
        return { system, electron };
      }
      await print(`Electron ${process.versions.electron}; Chromium ${process.versions.chrome}`);
      await pause(1500);
      await command('wl-copy', ['--type', 'text/plain;charset=utf-8'], 'A: external before');
      await pause(300);
      await snapshot('1. External copy A');
      await clipboard.writeText('B: Electron programmatic copy');
      await pause(300);
      await snapshot('2. Awaited Electron write B, without a new native input event');
      await command('wl-copy', ['--type', 'text/plain;charset=utf-8'], 'C: external after');
      await pause(300);
      const result = await snapshot('3. External copy C');
      await print(result.system === 'C: external after' && result.electron === 'B: Electron programmatic copy'
        ? 'REPRODUCED: Electron is stuck on B while the system clipboard is C.\nNow Ctrl+V into the box: affected Electron also pastes B.'
        : 'NOT REPRODUCED: keep the app untouched during the sequence and check the output above.');
      if (process.env.REPRO_AUTO_QUIT === '1') app.quit();
    }).catch(error => { console.error(error); app.exit(1); });
    
    app.on('window-all-closed', () => app.quit());
    JS
    ORCA_BACKGROUND_LAUNCH=1 WAYLAND_DEBUG=1 npx --yes [email protected] electron --no-sandbox --ozone-platform=wayland "$repro_dir/repro.cjs"

    Expected on a working implementation: step 2 reads B from both Electron and wl-paste; step 3 reads C from both.

    Actual output on the affected implementation:

    Electron 44.5.1; Chromium 152.0.7977.130
    1. External copy A
      wl-paste: "A: external before"
      Electron: "A: external before"
    2. Awaited Electron write B, without a new native input event
      wl-paste: "A: external before"
      Electron: "B: Electron programmatic copy"
    3. External copy C
      wl-paste: "C: external after"
      Electron: "B: Electron programmatic copy"
    REPRODUCED: Electron is stuck on B while the system clipboard is C.
    Now Ctrl+V into the box: affected Electron also pastes B.
    

    After it finishes, Ctrl+V into the provided textarea also pastes B, although wl-paste --no-newline in another terminal returns C. Further copies in other apps remain invisible to this Electron process. In the earlier diagnostic I verified this with real compositor keyboard input, not a simulated DOM paste.

    The initial A/A read checks that the app can read the real clipboard before its programmatic write. No click/key press is required to trigger the bug. The await is intentional: the new Promise API resolves even though the compositor never takes ownership of B.

    For a trace, WAYLAND_DEBUG=1 is already enabled. In the no-input case, Electron creates/offers a data source without sending wl_data_device.set_selection; incoming external selection offers still arrive afterward. In the stale-input variant, set_selection is sent with an older input serial and the compositor rejects it. Both leave Electron's local ownership/cache set. The script removes WAYLAND_DEBUG only from the wl-copy/wl-paste children to keep their output readable.

    Calling clipboard.clear() after the failed write restores reads of C in our tests, but doesn't make the attempted copy of B reach the system clipboard. A cache-only fix would prevent the stuck state while still dropping the programmatic copy.

  5. added theissue type on Oct 28, 2026
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

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions