Skip to content

Commit 0718aa9

Browse files
authored
native: reconnect the X11 clipboard after a connection failure (#1844)
After the X server or XWayland restarted, the clipboard service kept its dead X11 connection, and it only connects when it has none. Every later read or write failed until the app restarted, first with "Failed to request X11 clipboard conversion" and then with "X11 clipboard output flush failed". OpenCode users under WSLg reported exactly these errors. The connection now notices a lost server and is dropped once no pending X11 operation uses it, so later reads, writes and clears connect again, as Wayland already does. A read in flight fails at once instead of timing out, and an owned selection stops waking the drain timer. A reconnect that finds the server still down is retried later. Under WSLg, the X11 fallback goes through Weston's XWM, which can only bridge text. When Windows holds an image, it answers with zero bytes of text, so a paste read an empty text/plain. On WSL, a zero-byte X11 result now ends the read as empty. Real text still reads, and nothing changes off WSL. A host.zig table covers the reset, its guards, a lost server and the WSL rule; on a private Xvfb, reads, writes and clears after a server restart now succeed. Refs anomalyco/opencode#58466
1 parent 4c12eed commit 0718aa9

2 files changed

Lines changed: 143 additions & 42 deletions

File tree

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

Lines changed: 139 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,7 @@ pub const Service = struct {
824824
if (wslOperationUnsupported(libraries, operation)) {
825825
return service.finishOperation(operation, .unsupported);
826826
}
827+
service.resetFailedX11();
827828
operation.mechanism = operation.mechanism orelse if (libraries.wayland)
828829
.wayland
829830
else if (libraries.x11)
@@ -894,14 +895,19 @@ pub const Service = struct {
894895
return switch (service.x11.?.drive()) {
895896
.pending => .pending,
896897
.ready => null,
897-
.unsupported => service.finishOperation(operation, .unsupported),
898+
.unsupported => {
899+
const status = service.finishOperation(operation, .unsupported);
900+
service.resetFailedX11();
901+
return status;
902+
},
898903
.failed => service.finishX11Failure(operation),
899904
};
900905
}
901906

902907
fn driveX11(service: *Service, operation: *Operation) OperationStatus {
903908
if (service.ensureX11(operation)) |status| return status;
904909
service.driveX11EventUnit();
910+
if (service.x11.?.phase == .failed) return service.finishX11Failure(operation);
905911
return switch (operation.kind) {
906912
.read => service.driveX11Read(operation),
907913
.write => service.driveX11Write(operation),
@@ -1213,10 +1219,10 @@ pub const Service = struct {
12131219
if (operation.x11_read.phase != .idle) return .pending;
12141220
},
12151221
.ready => {
1216-
const empty_png = operation.result_mime.len > 0 and
1217-
std.ascii.eqlIgnoreCase(operation.result_mime, "image/png") and
1218-
operation.transfer_data.items.len == 0;
1219-
if (!empty_png) {
1222+
// WSLg's XWM answers UTF8_STRING with zero bytes when Windows holds an image.
1223+
const empty = operation.transfer_data.items.len == 0 and
1224+
(service.libraries.is_wsl or std.ascii.eqlIgnoreCase(operation.result_mime, "image/png"));
1225+
if (!empty) {
12201226
operation.result = operation.transfer_data.toOwnedSlice(operation.allocator) catch {
12211227
x11.cleanupRead(&operation.x11_read);
12221228
operation.rememberFailure(.out_of_memory, "Failed to allocate X11 clipboard result");
@@ -1251,10 +1257,7 @@ pub const Service = struct {
12511257
operation.diagnostic = "Failed to allocate X11 clipboard result";
12521258
return service.finishOperation(operation, .failed);
12531259
},
1254-
.failed => {
1255-
x11.cleanupRead(&operation.x11_read);
1256-
return service.finishX11Failure(operation);
1257-
},
1260+
.failed => return service.finishX11Failure(operation),
12581261
}
12591262

12601263
while (true) {
@@ -1266,9 +1269,8 @@ pub const Service = struct {
12661269
operation.x11_targets[operation.x11_target_index],
12671270
operation.max_bytes,
12681271
)) {
1269-
x11.cleanupRead(&operation.x11_read);
12701272
operation.rememberFailure(.x11_flush, "Failed to request X11 clipboard conversion");
1271-
return service.finishOperation(operation, .failed);
1273+
return service.finishX11Failure(operation);
12721274
}
12731275
return .pending;
12741276
}
@@ -1358,7 +1360,24 @@ pub const Service = struct {
13581360
.provider => operation.rememberFailure(.x11_provider, "X11 clipboard provider failed"),
13591361
}
13601362
operation.cleanupX11();
1361-
return service.finishOperation(operation, .failed);
1363+
const status = service.finishOperation(operation, .failed);
1364+
service.resetFailedX11();
1365+
return status;
1366+
}
1367+
1368+
// A failed or unsupported connection never recovers. Drop it once no pending operation holds
1369+
// X11 state, so the next operation connects again; each pending one fails on its next poll.
1370+
fn resetFailedX11(service: *Service) void {
1371+
const x11 = service.x11 orelse return;
1372+
if (x11.phase != .failed and x11.phase != .unsupported) return;
1373+
for (service.operations.items) |operation| {
1374+
operation.mutex.lock();
1375+
defer operation.mutex.unlock();
1376+
if (operation.status == .pending and operation.mechanism == .x11) return;
1377+
}
1378+
x11.deinit();
1379+
service.allocator.destroy(x11);
1380+
service.x11 = null;
13621381
}
13631382

13641383
fn hasEarlierSelectionMutation(service: *const Service, operation: *const Operation) bool {
@@ -2650,34 +2669,117 @@ test "clipboard X11 candidate failure advances to the next compatible target" {
26502669
try std.testing.expectEqual(@as(usize, 0), operation.transfer_data.items.len);
26512670
}
26522671

2653-
test "clipboard final X11 refusal cleans read state before publication" {
2654-
var symbols: clipboard_linux.XcbSymbols = undefined;
2655-
symbols.xcb_delete_property = testX11DeleteProperty;
2656-
symbols.xcb_destroy_window = testX11DestroyWindow;
2657-
var fake_connection: u8 = 0;
2658-
var x11 = clipboard_x11.Connection.init(std.testing.allocator, &symbols, 1);
2659-
x11.connection = @ptrCast(&fake_connection);
2660-
var service: Service = .{
2661-
.allocator = std.testing.allocator,
2662-
.objects = undefined,
2663-
.libraries = .{},
2664-
.x11 = &x11,
2665-
.requested_wayland_seat = &.{},
2666-
.environment_wayland_seat = &.{},
2672+
test "clipboard X11 read outcomes clean read state and drop a failed connection" {
2673+
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
2674+
const ServerGone = struct {
2675+
fn poll(_: *clipboard_linux.XcbConnection) callconv(.c) ?*clipboard_linux.XcbGenericEvent {
2676+
return null;
2677+
}
2678+
fn hasError(_: *clipboard_linux.XcbConnection) callconv(.c) c_int {
2679+
return 1;
2680+
}
2681+
fn disconnect(_: *clipboard_linux.XcbConnection) callconv(.c) void {}
26672682
};
2668-
var request = [_]u8{ 0, 0, 0, 0 };
2669-
var operation: Operation = .{
2670-
.allocator = std.testing.allocator,
2671-
.service = &service,
2672-
.kind = .read,
2673-
.request = &request,
2674-
.implemented_candidate_attempted = true,
2675-
.x11_read = .{ .phase = .refused, .window = 42 },
2676-
.x11_target_count = 1,
2683+
const Case = struct {
2684+
name: []const u8,
2685+
kind: OperationKind = .read,
2686+
mime: []const u8 = "text/plain",
2687+
read: clipboard_x11.ReadState = .{},
2688+
data: []const u8 = "",
2689+
wsl: bool = false,
2690+
phase: @FieldType(clipboard_x11.Connection, "phase") = .idle,
2691+
drive: enum { read, operation, drain } = .read,
2692+
other: ?clipboard_linux.Mechanism = null,
2693+
status: OperationStatus = .failed,
2694+
diagnostic: []const u8 = "X11 clipboard protocol failed",
2695+
dropped: bool = false,
26772696
};
2697+
const conversion = "Failed to request X11 clipboard conversion";
2698+
const cases = [_]Case{
2699+
.{ .name = "final refusal", .read = .{ .phase = .refused, .window = 42 }, .status = .empty, .diagnostic = "" },
2700+
.{ .name = "zero-byte text", .read = .{ .phase = .ready }, .status = .read, .diagnostic = "" },
2701+
.{ .name = "zero-byte png", .read = .{ .phase = .ready }, .mime = "image/png", .status = .empty, .diagnostic = "" },
2702+
.{ .name = "WSL zero-byte text", .read = .{ .phase = .ready }, .wsl = true, .status = .empty, .diagnostic = "" },
2703+
.{ .name = "WSL text", .read = .{ .phase = .ready }, .data = "x", .wsl = true, .status = .read, .diagnostic = "" },
2704+
.{ .name = "request, live connection", .diagnostic = conversion },
2705+
.{ .name = "request, failed connection", .phase = .failed, .diagnostic = conversion, .dropped = true },
2706+
.{ .name = "unsupported connection", .phase = .unsupported, .drive = .operation, .status = .unsupported, .diagnostic = "", .dropped = true },
2707+
.{ .name = "X11 read pending", .phase = .failed, .drive = .operation, .other = .x11 },
2708+
// A ready connection whose server went away.
2709+
.{ .name = "read in flight, server gone", .read = .{ .phase = .selection }, .phase = .ready, .drive = .operation, .dropped = true },
2710+
.{ .name = "write, server gone", .kind = .write, .phase = .ready, .drive = .operation, .dropped = true },
2711+
.{ .name = "clear, server gone", .kind = .clear, .phase = .ready, .drive = .operation, .dropped = true },
2712+
.{ .name = "owned selection, server gone", .phase = .ready, .drive = .drain },
2713+
};
2714+
for (cases) |case| {
2715+
errdefer std.debug.print("case: {s}\n", .{case.name});
2716+
var symbols: clipboard_linux.XcbSymbols = undefined;
2717+
symbols.xcb_poll_for_event = ServerGone.poll;
2718+
symbols.xcb_connection_has_error = ServerGone.hasError;
2719+
symbols.xcb_disconnect = ServerGone.disconnect;
2720+
var fake_connection: u8 = 0;
2721+
const x11 = try std.testing.allocator.create(clipboard_x11.Connection);
2722+
x11.* = clipboard_x11.Connection.init(std.testing.allocator, &symbols, 1);
2723+
x11.phase = case.phase;
2724+
if (case.phase == .ready) x11.connection = @ptrCast(&fake_connection);
2725+
var service: Service = .{
2726+
.allocator = std.testing.allocator,
2727+
.objects = undefined,
2728+
.libraries = .{ .is_wsl = case.wsl },
2729+
.x11 = x11,
2730+
.requested_wayland_seat = &.{},
2731+
.environment_wayland_seat = &.{},
2732+
};
2733+
defer if (service.x11) |left| {
2734+
left.deinit();
2735+
std.testing.allocator.destroy(left);
2736+
};
2737+
var request = [_]u8{ 0, 0, 0, 0 };
2738+
var operation: Operation = .{
2739+
.allocator = std.testing.allocator,
2740+
.service = &service,
2741+
.kind = case.kind,
2742+
.request = &request,
2743+
.mechanism = .x11,
2744+
.implemented_candidate_attempted = true,
2745+
.result_mime = try std.testing.allocator.dupe(u8, case.mime),
2746+
.x11_read = case.read,
2747+
.x11_targets = .{0} ** 6,
2748+
.x11_target_count = 1,
2749+
};
2750+
defer operation.transfer_data.deinit(std.testing.allocator);
2751+
defer std.testing.allocator.free(operation.result);
2752+
defer std.testing.allocator.free(operation.result_mime);
2753+
try operation.transfer_data.appendSlice(std.testing.allocator, case.data);
2754+
var other: Operation = .{ .allocator = std.testing.allocator, .service = &service, .kind = .read, .mechanism = case.other };
2755+
var storage = [_]*Operation{ &operation, &other };
2756+
service.operations = .{ .items = &storage, .capacity = storage.len };
2757+
2758+
if (case.drive == .drain) {
2759+
const provider = try std.testing.allocator.create(clipboard_x11.Provider);
2760+
provider.* = .{ .selection = 1, .data = &.{} };
2761+
x11.providers[0] = provider;
2762+
x11.clipboard_provider = provider;
2763+
service.driveX11EventUnit();
2764+
try std.testing.expect(!x11.driveProviderUnit());
2765+
try std.testing.expect(x11.providers[0] == null);
2766+
continue;
2767+
}
2768+
const status = if (case.drive == .operation) service.driveX11(&operation) else service.driveX11Read(&operation);
2769+
try std.testing.expectEqual(case.status, status);
2770+
try std.testing.expectEqualStrings(case.diagnostic, operation.diagnostic);
2771+
try std.testing.expectEqualStrings(case.data, operation.result);
2772+
try std.testing.expectEqual(clipboard_x11.ReadState{}, operation.x11_read);
2773+
try std.testing.expectEqual(case.dropped, service.x11 == null);
2774+
if (case.other == null) continue;
26782775

2679-
try std.testing.expectEqual(OperationStatus.empty, service.driveX11Read(&operation));
2680-
try std.testing.expectEqual(clipboard_x11.ReadState{}, operation.x11_read);
2776+
// Once the pending sibling is cancelled, the next operation drops the dead connection.
2777+
try std.testing.expectEqual(CancelStatus.requested, other.requestCancel());
2778+
var text_request = [_]u8{ 0, 0, 0, 0, 10, 0, 0, 0 } ++ "text/plain".*;
2779+
var next: Operation = .{ .allocator = std.testing.allocator, .service = &service, .kind = .read, .request = &text_request };
2780+
try std.testing.expectEqual(OperationStatus.unsupported, service.driveOperation(&next));
2781+
try std.testing.expect(service.x11 == null);
2782+
}
26812783
}
26822784

26832785
test "clipboard shutdown cancels unconfirmed X11 mutations before releasing providers" {
@@ -2743,10 +2845,6 @@ fn testX11DestroyWindow(_: *clipboard_linux.XcbConnection, _: u32) callconv(.c)
27432845
return .{ .sequence = 1 };
27442846
}
27452847

2746-
fn testX11DeleteProperty(_: *clipboard_linux.XcbConnection, _: u32, _: u32) callconv(.c) clipboard_linux.XcbCookie {
2747-
return .{ .sequence = 1 };
2748-
}
2749-
27502848
fn testX11SetSelectionOwner(
27512849
_: *clipboard_linux.XcbConnection,
27522850
_: u32,

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,7 +1042,10 @@ pub const Connection = struct {
10421042
pub fn pollEvent(self: *Connection) ?*linux.XcbGenericEvent {
10431043
const connection = self.connection orelse return null;
10441044
if (self.phase != .ready) return null;
1045-
return self.symbols.xcb_poll_for_event(connection);
1045+
const event = self.symbols.xcb_poll_for_event(connection);
1046+
// xcb reports a lost server only through the connection error; nothing else polls it once ready.
1047+
if (event == null and self.symbols.xcb_connection_has_error(connection) != 0) _ = self.fail(.connection);
1048+
return event;
10461049
}
10471050

10481051
pub fn handleProviderEvent(self: *Connection, event: *const linux.XcbGenericEvent) void {

0 commit comments

Comments
 (0)