Skip to content

Commit 87562e7

Browse files
authored
native: retry an unsupported Wayland clipboard connection (#1845)
When the Wayland clipboard could not connect, or the compositor had no seat or no clipboard protocol, the service kept that `unsupported` result for its whole life. Every later read fell back to X11 even after the socket appeared. Under WSLg the X11 bridge returns a 0-byte text for an image, so image paste stayed broken for the rest of the session. This is what anomalyco/opencode#57724 and #58466 report, where `XDG_RUNTIME_DIR` does not contain the WSLg socket. The idle drain now closes an unsupported connection like any other idle one, so the next operation tries again. That costs at most one connect per operation, never one per poll. On WSL only, a failed connect also tries `/mnt/wslg/runtime-dir/$WAYLAND_DISPLAY`, the path the reporters used as a workaround. The default connect is skipped when libwayland would refuse it (no absolute `XDG_RUNTIME_DIR` or `WAYLAND_DISPLAY`), so its "XDG_RUNTIME_DIR is invalid" line does not reach the terminal on every paste. Native tests cover the retry bound, the connect order, the WSL-only fallback and the host's WSL flag. On a nested compositor whose socket appears after the first read, the later reads now return `image/png` instead of `unsupported`.
1 parent de63ba8 commit 87562e7

3 files changed

Lines changed: 145 additions & 40 deletions

File tree

‎packages/native/src/clipboard/host.zig‎

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -857,7 +857,7 @@ pub const Service = struct {
857857
service.environment_wayland_seat,
858858
service.max_provider_transfers,
859859
);
860-
wayland.allow_core_data_device = libraries.is_wsl;
860+
wayland.is_wsl = libraries.is_wsl;
861861
service.wayland = wayland;
862862
}
863863
return switch (service.wayland.?.drive()) {
@@ -2494,6 +2494,7 @@ test "clipboard drain closes the Wayland connection only when nothing needs it"
24942494
output_pending: bool = false,
24952495
phase: enum { ready, unsupported, failed } = .ready,
24962496
inherited_socket: bool = false,
2497+
connected: bool = true,
24972498
open: bool,
24982499
};
24992500
const cases = [_]Case{
@@ -2507,7 +2508,8 @@ test "clipboard drain closes the Wayland connection only when nothing needs it"
25072508
.{ .name = "owned primary selection", .provider = true, .primary = true, .open = true },
25082509
.{ .name = "selection barrier", .barrier = true, .open = true },
25092510
.{ .name = "queued output", .output_pending = true, .open = true },
2510-
.{ .name = "cached unsupported probe", .phase = .unsupported, .open = true },
2511+
.{ .name = "unsupported registry", .phase = .unsupported, .open = false },
2512+
.{ .name = "failed connect", .phase = .unsupported, .connected = false, .open = false },
25112513
.{ .name = "failed connection", .phase = .failed, .open = false },
25122514
.{ .name = "inherited WAYLAND_SOCKET", .inherited_socket = true, .open = true },
25132515
};
@@ -2522,7 +2524,10 @@ test "clipboard drain closes the Wayland connection only when nothing needs it"
25222524
const service = acquireService(&objects, service_handle).?;
25232525
service.libraries = .{ .wayland = true };
25242526
const wayland = try std.testing.allocator.create(clipboard_wayland.Connection);
2525-
wayland.* = clipboard_wayland.testReadyConnection(&symbols, .{ .result = 0, .errno = .SUCCESS });
2527+
wayland.* = if (case.connected)
2528+
clipboard_wayland.testReadyConnection(&symbols, .{ .result = 0, .errno = .SUCCESS })
2529+
else
2530+
clipboard_wayland.Connection.init(std.testing.allocator, &symbols, "", "", 1);
25262531
service.wayland = wayland;
25272532
if (case.provider) {
25282533
const data = try std.testing.allocator.dupe(u8, "owned");
@@ -2557,7 +2562,7 @@ test "clipboard drain closes the Wayland connection only when nothing needs it"
25572562
try std.testing.expectEqual(@as(u8, @intFromBool(active)), drainService(&objects, service_handle));
25582563
try std.testing.expectEqual(case.open, service.wayland != null);
25592564
// Queued events are dispatched before a close so their offers are destroyed.
2560-
try std.testing.expectEqual(@intFromBool(!case.open), Dispatch.count);
2565+
try std.testing.expectEqual(@intFromBool(!case.open and case.connected), Dispatch.count);
25612566
}
25622567
}
25632568

@@ -2584,6 +2589,34 @@ test "clipboard Wayland fallback transitions to X11 only when available" {
25842589
try std.testing.expectEqual(clipboard_linux.Mechanism.wayland, operation.mechanism.?);
25852590
}
25862591

2592+
test "clipboard Wayland connection takes WSL detection from the service" {
2593+
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
2594+
const Refuse = struct {
2595+
fn connect(_: ?[*:0]const u8) callconv(.c) ?*clipboard_linux.WlDisplay {
2596+
return null;
2597+
}
2598+
};
2599+
var symbols = clipboard_wayland.testSymbols();
2600+
symbols.wl_display_connect = Refuse.connect;
2601+
const previous = clipboard_linux.testSwapWaylandSymbols(symbols);
2602+
defer _ = clipboard_linux.testSwapWaylandSymbols(previous);
2603+
for ([_]bool{ false, true }) |is_wsl| {
2604+
var service: Service = .{
2605+
.allocator = std.testing.allocator,
2606+
.objects = undefined,
2607+
.libraries = .{ .wayland = true, .is_wsl = is_wsl },
2608+
.requested_wayland_seat = &.{},
2609+
.environment_wayland_seat = &.{},
2610+
};
2611+
defer service.resetWayland();
2612+
var operation: Operation = .{ .allocator = std.testing.allocator, .service = &service, .kind = .read };
2613+
2614+
try std.testing.expectEqual(OperationStatus.unsupported, service.driveWayland(&operation, service.libraries));
2615+
// The WSLg socket fallback and the core data device both follow this flag.
2616+
try std.testing.expectEqual(is_wsl, service.wayland.?.is_wsl);
2617+
}
2618+
}
2619+
25872620
test "clipboard X11 candidate failure advances to the next compatible target" {
25882621
var symbols: clipboard_linux.XcbSymbols = undefined;
25892622
var fake_connection: u8 = 0;

‎packages/native/src/clipboard/linux.zig‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,3 +452,12 @@ test "clipboard XCB ABI types match the core protocol layouts" {
452452
try std.testing.expectEqual(@as(usize, 28), @sizeOf(XcbSelectionRequestEvent));
453453
try std.testing.expectEqual(@as(usize, 24), @sizeOf(XcbSelectionNotifyEvent));
454454
}
455+
456+
// Replaces the loaded libwayland symbols so host tests can create a connection; returns the previous ones.
457+
pub fn testSwapWaylandSymbols(symbols: ?WaylandSymbols) ?WaylandSymbols {
458+
cache_mutex.lock();
459+
defer cache_mutex.unlock();
460+
const previous = wayland_cache.symbols;
461+
wayland_cache.symbols = symbols;
462+
return previous;
463+
}

‎packages/native/src/clipboard/wayland.zig‎

Lines changed: 99 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ pub const Connection = struct {
144144
clipboard_provider: ?*Provider = null,
145145
primary_provider: ?*Provider = null,
146146
provider_cursor: u8 = 0,
147-
allow_core_data_device: bool = false,
147+
is_wsl: bool = false,
148148
flush_outcome_override: ?FlushOutcome = null,
149149
test_marshal_count: u8 = 0,
150150
test_flush_marshal_count: u8 = 0,
@@ -445,10 +445,10 @@ pub const Connection = struct {
445445
}
446446

447447
// An idle connection still receives an offer for every selection change, so the host
448-
// closes it and reconnects on demand. An unsupported result binds no device and stays
449-
// cached, and an inherited socket cannot be reopened after libwayland consumed it.
448+
// closes it and reconnects on demand. Closing an unsupported result retries it on the next
449+
// operation, and an inherited socket cannot be reopened after libwayland consumed it.
450450
pub fn closableWhenIdle(self: *const Connection) bool {
451-
return self.phase != .unsupported and !self.inherited_socket and !self.hasWork();
451+
return !self.inherited_socket and !self.hasWork();
452452
}
453453

454454
// Events already read from the socket may create offer proxies. Dispatching them
@@ -525,8 +525,16 @@ pub const Connection = struct {
525525

526526
fn start(self: *Connection) !void {
527527
// libwayland adopts and unsets an inherited WAYLAND_SOCKET, so record it before connecting.
528-
const inherited_socket = posix_io.getEnv("WAYLAND_SOCKET") != null;
529-
const display = self.symbols.wl_display_connect(null) orelse return error.ConnectFailed;
528+
var inherited_socket = posix_io.getEnv("WAYLAND_SOCKET") != null;
529+
// libwayland refuses a relative name without an absolute XDG_RUNTIME_DIR and logs each
530+
// refusal to stderr, which is the terminal; skip the attempt instead of repeating the line.
531+
const runtime_dir = posix_io.getEnv("XDG_RUNTIME_DIR") orelse "";
532+
const name = posix_io.getEnv("WAYLAND_DISPLAY") orelse "";
533+
const absolute = std.mem.startsWith(u8, runtime_dir, "/") or std.mem.startsWith(u8, name, "/");
534+
const display = (if (inherited_socket or absolute) self.symbols.wl_display_connect(null) else null) orelse wslg: {
535+
inherited_socket = false;
536+
break :wslg self.connectWslg() orelse return error.ConnectFailed;
537+
};
530538
self.inherited_socket = inherited_socket;
531539
// libwayland before 1.23 has no cap symbol and uses fixed-size bounded buffers instead.
532540
if (self.symbols.wl_display_set_max_buffer_size) |set_max_buffer_size| {
@@ -542,6 +550,16 @@ pub const Connection = struct {
542550
if (self.queueFlush() == .failed) return error.FlushFailed;
543551
}
544552

553+
// WSLg keeps its socket here, and an XDG_RUNTIME_DIR that does not link it hides it
554+
// from libwayland (anomalyco/opencode#57724, #58466).
555+
fn connectWslg(self: *Connection) ?*linux.WlDisplay {
556+
if (!self.is_wsl) return null;
557+
const name = posix_io.getEnv("WAYLAND_DISPLAY") orelse return null;
558+
var buffer: [std.fs.max_path_bytes:0]u8 = undefined;
559+
const path = std.fmt.bufPrintZ(&buffer, "/mnt/wslg/runtime-dir/{s}", .{name}) catch return null;
560+
return self.symbols.wl_display_connect(path);
561+
}
562+
545563
fn sendSync(self: *Connection) bool {
546564
const display = self.display orelse return false;
547565
const callback = self.marshal(@ptrCast(display), 0, self.symbols.wl_callback_interface, 1, &.{}) orelse
@@ -821,7 +839,7 @@ pub const Connection = struct {
821839
}
822840

823841
fn coreDataDeviceAvailable(self: *const Connection) bool {
824-
return self.allow_core_data_device and self.core_manager_global != null and
842+
return self.is_wsl and self.core_manager_global != null and
825843
self.compositor_global != null and self.shm_global != null and self.shell_global != null;
826844
}
827845

@@ -1422,42 +1440,87 @@ test "Wayland core helper destroys its role before its surface" {
14221440
try std.testing.expectEqualSlices([2]usize, &expected, test_role_destroyed[0..test_role_destroy_count]);
14231441
}
14241442

1425-
test "Wayland connection setup applies the finite receive buffer cap and records an inherited socket" {
1443+
test "Wayland connection setup caps the receive buffer, records an inherited socket, and tries WSLg on WSL" {
14261444
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
14271445
const Environment = struct {
14281446
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
14291447
extern "c" fn unsetenv(name: [*:0]const u8) c_int;
1448+
var refused: enum { none, default, all } = .none;
1449+
var path: [64]u8 = undefined;
1450+
var path_length: usize = 0;
1451+
var count: u8 = 0;
14301452
// Like libwayland, connecting consumes an inherited WAYLAND_SOCKET.
1431-
fn connect(_: ?[*:0]const u8) callconv(.c) ?*linux.WlDisplay {
1453+
fn connect(name: ?[*:0]const u8) callconv(.c) ?*linux.WlDisplay {
14321454
_ = unsetenv("WAYLAND_SOCKET");
1433-
return @ptrFromInt(1);
1455+
count += 1;
1456+
const explicit = name orelse return if (refused == .none) @ptrFromInt(1) else null;
1457+
path_length = std.mem.len(explicit);
1458+
@memcpy(path[0..path_length], explicit[0..path_length]);
1459+
return if (refused == .all) null else @ptrFromInt(1);
14341460
}
14351461
};
1462+
const Case = struct {
1463+
// libwayland before 1.23 has no cap symbol and already uses fixed-size bounded buffers.
1464+
cap: bool = true,
1465+
inherited: bool = false,
1466+
refused: @TypeOf(Environment.refused) = .none,
1467+
wsl: bool = false,
1468+
progress: Progress = .pending,
1469+
wslg_path: []const u8 = "",
1470+
connects: u8 = 1,
1471+
runtime_dir: bool = true,
1472+
};
1473+
const wslg_path = "/mnt/wslg/runtime-dir/wayland-7";
1474+
const cases = [_]Case{
1475+
.{ .inherited = true, .runtime_dir = false },
1476+
.{ .cap = false },
1477+
.{ .refused = .default, .progress = .unsupported },
1478+
.{ .wsl = true },
1479+
.{ .refused = .default, .wsl = true, .inherited = true, .wslg_path = wslg_path, .connects = 2 },
1480+
.{ .refused = .all, .wsl = true, .progress = .unsupported, .wslg_path = wslg_path, .connects = 2 },
1481+
// libwayland would refuse the relative name and log to stderr on every operation.
1482+
.{ .runtime_dir = false, .wsl = true, .wslg_path = wslg_path },
1483+
};
1484+
const names = [_][*:0]const u8{ "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR" };
1485+
var saved: [names.len]?[:0]u8 = undefined;
1486+
for (names, &saved) |name, *value| {
1487+
value.* = if (posix_io.getEnv(name)) |current| try std.testing.allocator.dupeZ(u8, current) else null;
1488+
}
1489+
defer for (names, saved) |name, value| {
1490+
if (value) |restored| {
1491+
_ = Environment.setenv(name, restored, 1);
1492+
std.testing.allocator.free(restored);
1493+
} else _ = Environment.unsetenv(name);
1494+
};
1495+
try std.testing.expectEqual(@as(c_int, 0), Environment.setenv("WAYLAND_DISPLAY", "wayland-7", 1));
14361496
var symbols = testSymbols();
14371497
symbols.wl_display_connect = Environment.connect;
1438-
symbols.wl_display_set_max_buffer_size = testSetMaxBufferSize;
1439-
var connection = Connection.init(std.testing.allocator, &symbols, "", "", 1);
1440-
connection.flush_outcome_override = .{ .result = 0, .errno = .SUCCESS };
1441-
test_max_buffer_size = 0;
1442-
try std.testing.expectEqual(@as(c_int, 0), Environment.setenv("WAYLAND_SOCKET", "99", 1));
1443-
defer _ = Environment.unsetenv("WAYLAND_SOCKET");
1444-
1445-
try connection.start();
1446-
1447-
try std.testing.expectEqual(@as(usize, WAYLAND_CONNECTION_BUFFER_SIZE_MAX), test_max_buffer_size);
1448-
try std.testing.expect(connection.inherited_socket);
1449-
1450-
// libwayland before 1.23 has no cap symbol; setup must still succeed because
1451-
// those versions already use fixed-size bounded connection buffers.
1452-
symbols.wl_display_set_max_buffer_size = null;
1453-
var uncapped = Connection.init(std.testing.allocator, &symbols, "", "", 1);
1454-
uncapped.flush_outcome_override = .{ .result = 0, .errno = .SUCCESS };
1455-
test_max_buffer_size = 0;
1456-
1457-
try uncapped.start();
1458-
1459-
try std.testing.expectEqual(@as(usize, 0), test_max_buffer_size);
1460-
try std.testing.expect(!uncapped.inherited_socket);
1498+
for (cases) |case| {
1499+
symbols.wl_display_set_max_buffer_size = if (case.cap) testSetMaxBufferSize else null;
1500+
var connection = Connection.init(std.testing.allocator, &symbols, "", "", 1);
1501+
connection.is_wsl = case.wsl;
1502+
connection.flush_outcome_override = .{ .result = 0, .errno = .SUCCESS };
1503+
test_max_buffer_size = 0;
1504+
Environment.refused = case.refused;
1505+
Environment.path_length = 0;
1506+
Environment.count = 0;
1507+
if (case.runtime_dir) {
1508+
try std.testing.expectEqual(@as(c_int, 0), Environment.setenv("XDG_RUNTIME_DIR", "/run/user/test", 1));
1509+
} else _ = Environment.unsetenv("XDG_RUNTIME_DIR");
1510+
if (case.inherited) try std.testing.expectEqual(@as(c_int, 0), Environment.setenv("WAYLAND_SOCKET", "99", 1));
1511+
defer _ = Environment.unsetenv("WAYLAND_SOCKET");
1512+
1513+
try std.testing.expectEqual(case.progress, connection.drive());
1514+
1515+
const cap: usize = if (case.cap and case.progress != .unsupported) WAYLAND_CONNECTION_BUFFER_SIZE_MAX else 0;
1516+
try std.testing.expectEqual(cap, test_max_buffer_size);
1517+
try std.testing.expectEqualStrings(case.wslg_path, Environment.path[0..Environment.path_length]);
1518+
// A WSLg connection is not the inherited socket, so the idle drain may close it.
1519+
try std.testing.expectEqual(case.inherited and case.refused == .none, connection.inherited_socket);
1520+
// Later drives reuse the result; only the host's idle close lets an operation connect again.
1521+
for (0..3) |_| _ = connection.drive();
1522+
try std.testing.expectEqual(case.connects, Environment.count);
1523+
}
14611524
}
14621525

14631526
test "Wayland dispatch drains queued callbacks up to the per-drive bound" {
@@ -1834,13 +1897,13 @@ fn testOfferConnection(proxy: *WlProxy) Connection {
18341897

18351898
test "Wayland core data-device fallback is WSL-gated and read-only" {
18361899
var connection: Connection = undefined;
1837-
connection.allow_core_data_device = false;
1900+
connection.is_wsl = false;
18381901
connection.core_manager_global = 1;
18391902
connection.compositor_global = 2;
18401903
connection.shm_global = 3;
18411904
connection.shell_global = 4;
18421905
try std.testing.expect(!connection.coreDataDeviceAvailable());
1843-
connection.allow_core_data_device = true;
1906+
connection.is_wsl = true;
18441907
try std.testing.expect(connection.coreDataDeviceAvailable());
18451908

18461909
connection.core_data_device = true;
@@ -1874,7 +1937,7 @@ test "Wayland core helper requires an advertised keyboard capability" {
18741937
Connection.seatCapabilities(&connection, seat_proxy, 0);
18751938
try std.testing.expectEqual(@as(u32, 0), connection.seats[0].capabilities);
18761939

1877-
connection.allow_core_data_device = true;
1940+
connection.is_wsl = true;
18781941
connection.core_manager_global = 1;
18791942
connection.compositor_global = 2;
18801943
connection.shm_global = 3;

0 commit comments

Comments
 (0)