Skip to content

Fix repeated Vim copies hanging the IDE on Wayland - #171

Merged
ernestrc merged 8 commits into
unstablebuild:mainfrom
santhiprakash:fix/170-clipboard-copy-burst
Oct 4, 2026
Merged

ernestrc merged 8 commits into
unstablebuild:mainfrom
santhiprakash:fix/170-clipboard-copy-burst

Conversation

@santhiprakash

@santhiprakash santhiprakash commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Holding . to repeat a Vim dw hangs the IDE on Wayland (#170).

Root cause

systemClipboard.Copy performs OS clipboard I/O synchronously on the event
loop goroutine: sysclip.Copy → atotto/clipboard.WriteAll → exec wl-copy

  • Wait. Each invocation is a subprocess spawn plus a Wayland selection
    round-trip, and wl-copy stays resident serving the selection. A single copy
    can block input handling; a held . repeat turns that into an unbroken stall.

Fix

New internal/text/async_clipboard.go moves OS writes off the caller's
goroutine (review feedback — systemClipboard itself is left untouched):

  • asyncRegister is a private clipboard.Register wrapper, constructed by
    NewAsyncSystemClipboard(), which builds the system clipboard internally so
    the wrapper can assume register semantics.
  • Default-register copies are published to a buffered channel of size 1
    drained by a worker goroutine. When the worker is busy the slot is consumed
    and replaced — last copy wins, no locks, and a burst costs at most two OS
    writes: the one in flight plus the newest payload.
  • Named registers are in-memory writes, so they forward synchronously and stay
    in order; the slot only ever holds default-register payloads, so no
    cross-register discard is possible.
  • Paste stays synchronous, but while a write is queued or in flight the OS
    clipboard is not authoritative, so it returns the newest copy (tracked
    atomically alongside a pending counter) instead of reading stale content.

All three clipboard construction sites (cmd/rune, cmd/rune-agent,
clipboard: "system" config) now use NewAsyncSystemClipboard().

Verification

  • TestAsyncClipboardCopyNeverBlocksOnOSWrite (new): 51 copies across an
    in-flight OS write all return without blocking, exactly 2 writes reach the
    OS layer, newest payload last. Sabotage-checked: the same flow deadlocks
    against the previous synchronous systemClipboard — the very first Copy
    blocks the caller behind the write.
  • TestAsyncClipboardForwardsNamedRegistersSynchronously: named registers
    reach the wrapped clipboard before Copy returns.
  • TestAsyncClipboardPasteReadsNewestCopyWhileWriteInFlight: paste during an
    in-flight write returns the newest copy without touching the OS layer; once
    settled, paste reads the OS clipboard again.
  • go test -race ./internal/text/ ./internal/extension/extutil/ — ok
  • go test -vet=off ./... under xvfb-run -a — green except
    internal/llm/gemini TestModelsFallsBackOnMissingClient, which needs a
    live API call and fails identically without this change (env has real
    Gemini keys set). go vet / gofmt clean.

Notes

  • Fixes Repeated Vim copying hangs the IDE #170.
  • Worker write errors are dropped intentionally: Copy can no longer return
    the OS write error synchronously, and Paste still surfaces a broken or
    missing provider (e.g. the "install wl-clipboard" hint) on read.

Every default-register copy shelled out to a fresh wl-copy subprocess on
Wayland, so holding `.` to repeat a Vim delete spawned one subprocess per
repeat and hung the IDE.

A copy that arrives while an OS write is in flight now coalesces into a
single pending slot drained by one worker, so a burst costs at most one
extra subprocess and the newest payload still wins. The in-memory shadow
keeps every copy synchronously, so in-process registers are unaffected.

Fixes unstablebuild#170

Signed-off-by: Santhi Prakash <[email protected]>
@codecov-commenter

codecov-commenter commented Sep 30, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 82.60870% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/text/async_clipboard.go 90.47% 2 Missing ⚠️
cmd/rune-agent/extension/handler.go 0.00% 1 Missing ⚠️
internal/extension/extutil/config.go 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@ernestrc

Copy link
Copy Markdown
Contributor

The root cause behind #170 is not the repeat (although it contributes to reproducing it), is that we're performing potentially blocking I/O on the event loop goroutine. The solution therefore, is not to coalesce subsequent copies, it's to move the I/O to a separate goroutine altogether.

I propose the following design. Leave the systemClipboard as it is; it does already too many things but currently it's simple enough that it's easy to debug and understand. Instead, add a new clipboard.Register implementation, a private type, which wraps another clipboard.Register to "add" asynchronous Copy:

// internal/text/async_clipboard.go
package text

type asyncRegister struct {
  other clipboard.Register
}

type payload struct {
  registerID string, data clipboard.Data
}

func NewAsyncClipboard(other clipboard.Register) clipboard.Register {
   ret := &asyncRegister{other: other}
   ret.ch = make(chan payload, 1)
   go ret.startWorker()
   return ret
}

// etc.

Note how the channel is a buffered channel of size 1. This yields some very important semantics: the publisher of the channel can replace the payload when the worker is busy, effectively implementing last copy wins semantics, and even discarding worthless work in the case the worker is slow.

func (r *asyncRegister) Copy(registerID string, data clipboard.Data) error {
	p := payload{registerID: registerID, data: data}
	for {
	       // try to publish normally
		select {
		case r.ch <- p:
			return nil
		default:
		}
		// if the worker is busy, last copy wins; consume it
		// then publish
		select {
		case <-r.ch:
		default:
		}
	}
}

Taking advantage of the last copy wins semantics we get to something quite elegant, easy to test, and decoupled from whether the actual system clipboard implementation. Also:

•No lock is needed. Every round of the loop either publishes or frees the slot, so concurrent callers can't make Copy block on the worker.
•A burst costs at most two OS writes: the one in flight and the final one.

One minor drawback from this approach, although I think it's acceptable: There's only one register slot, so a copy to register a would discard a pending copy to the default register. Only the default register reaches the OS in systemClipboard anyway. So Copy should forward non-default registers to other synchronously and only queue clipboard.DefaultRegisterID. That writes named registers to memory in order and keeps the cross-register discard from happening.

Working around that in a generic wrapper means special-casing the default register. That quietly ties the wrapper to what systemClipboard does, which is the kind of hidden behavior I want to avoid. Instead, we could actually specialize it, and instantiate the system clipboard in its constructor, so we can now make assumptions about register ids.

// NewAsyncSystemClipboard wraps a system clipboard to provide asynchronous copy semantics..
func NewAsyncSystemClipboard() clipboard.Register {
   sys := NewSystemClipboard()
   ret := &asyncRegister{other: sys}
   ret.ch = make(chan payload, 1)
   go ret.startWorker()
   return ret
}

So tightening down the behavior:

  • Only the default register reaches the OS, so only the default register is queued.
  • Named registers are in-memory writes, so they're forwarded synchronously and stay in order.
  • The slot only ever holds default-register payloads, so the cross-register discard can't happen.
  • Paste stays synchronous. To avoid a stale paste due to a the copy goroutine racing the event loop goroutine, we should probably store an atomic with the last Copy, preserving last copy wins semantics, and if there's an inflight copy (the worker is not idle), we skip the system clipboard, since if there's an write in process the content of the OS clipboard is not authoritative anyway.

Review feedback on unstablebuild#170: the root cause is not the copy rate but blocking
I/O on the event loop goroutine — systemClipboard.Copy shells out to
wl-copy synchronously, so even the first write stalls input handling.

Leave systemClipboard untouched and add asyncRegister, a clipboard.Register
wrapper that queues only the default register onto a single-slot channel
drained by a worker. Publishers replace the slot when the worker is busy,
so last copy wins and a burst costs at most two OS writes. Named registers
are forwarded synchronously (in-memory writes, in order), and Paste answers
from the newest copy while a write is queued or in flight since the OS
clipboard is not authoritative then.

Refs unstablebuild#170

Signed-off-by: Santhi Prakash <[email protected]>
@santhiprakash

Copy link
Copy Markdown
Contributor Author

You're right — verified the claim before reworking: with a stub register whose Copy blocks mid-write, a single systemClipboard.Copy blocks the caller until the write finishes, so even the first copy stalls the event loop, not just the repeats. Reworked along your sketch in a4102d2:

  • internal/text/async_clipboard.go adds the private asyncRegister + NewAsyncSystemClipboard(), which constructs the system clipboard internally. systemClipboard itself is back to upstream, untouched.
  • Buffered channel of size 1 with the consume-and-replace publish loop — last copy wins, a burst costs at most the in-flight write plus the newest queued payload, no locks.
  • Only clipboard.DefaultRegisterID is queued; named registers forward synchronously so they stay in order. Since the slot only ever holds the default register, it's a chan clipboard.Data rather than carrying a registerID.
  • Paste stays synchronous. An atomic pending counter (incremented on publish, released when the worker finishes a write or a publisher discards it) plus an atomically stored newest copy makes Paste return the newest payload while a write is queued or in flight, deferring to the OS clipboard once settled.
  • The worker runs under debug.CapturePanicReport per AGENTS.md, and all three construction sites (cmd/rune, cmd/rune-agent, the clipboard: "system" config branch) now use NewAsyncSystemClipboard().

Verification:

go test -race -run 'TestAsyncClipboard|TestSystemClipboard' -v ./internal/text/
--- PASS: TestAsyncClipboardCopyNeverBlocksOnOSWrite (0.00s)
--- PASS: TestAsyncClipboardForwardsNamedRegistersSynchronously (0.00s)
--- PASS: TestAsyncClipboardPasteReadsNewestCopyWhileWriteInFlight (0.00s)
--- PASS: TestSystemClipboard* (all pre-existing)

TestAsyncClipboardCopyNeverBlocksOnOSWrite drives 51 copies across a gated in-flight write and asserts the callers never block — the same flow deadlocks against the synchronous path (confirms the event-loop diagnosis). go test -vet=off ./... is green under xvfb-run -a, apart from internal/llm/gemini's TestModelsFallsBackOnMissingClient, which makes a live API call and fails identically on a clean tree.

One behavior change worth flagging: Copy on the default register can no longer return the OS write error synchronously. Paste still surfaces a broken or missing provider (including the "install wl-clipboard" hint), just on read instead of write.

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

LGTM but I'll wait for @zhengqunkoo's feedback and testing before merging.

@santhiprakash

Copy link
Copy Markdown
Contributor Author

Heads-up on the red ubuntu-24.04 leg — both failures are outside this diff:

internal/text is green on both legs. Once the preset expectation is fixed on main I can merge it into the branch to refresh checks.

@santhiprakash

Copy link
Copy Markdown
Contributor Author

Merged current main in (3c26225) — picks up 0ea213b's TestRenderPreset fix plus the newer terminal/shell commits, so the previous preset failure is resolved at the source. If ubuntu-24.04 goes red again it should only be the TestConcurrentUpAfterLogout flake also seen on main.

@santhiprakash santhiprakash mentioned this pull request Oct 1, 2026
2 tasks done
@ernestrc
ernestrc merged commit e428893 into unstablebuild:main Oct 4, 2026
8 checks passed
@zhengqunkoo

zhengqunkoo commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

LGTM but I'll wait for @zhengqunkoo's feedback and testing before merging.

Apologies, was hunkered down with another issue.

On testing with deleting words on a line with dw., it needs some time to warm up: it lags at first, hangs around the 3rd word, and shows the "wl-clipboard is ready" system notification, and I was worried it would hang again. But then deleting became fast, and the system behaves as expected.

However, after a few minutes (typing out this comment), redoing the test repeats the warm-up behavior: it lags again for a while. Perhaps this is an issue with how Rune interacts with the wl-clipboard.

Despite this unresolved issue, the IDE no longer hangs indefinitely, so this PR is a big improvement over the previous state of things.

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.

Repeated Vim copying hangs the IDE

4 participants