Skip to content

Commit 1052174

Browse files
fix(tui): read clipboard images through Windows interop on WSL
The native host clipboard cannot read the Windows selection from WSL, so pasting a screenshot did nothing. Fall back to powershell.exe and report interop failures instead of returning undefined.
1 parent 3b593dd commit 1052174

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

‎packages/tui/src/clipboard.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ export function createClipboardAdapter(clipboard: CoreClipboardService): OwnedCl
3232
if (result.status === "limit-exceeded") {
3333
throw new RangeError("Clipboard content exceeded configured read or image conversion limits")
3434
}
35-
return undefined
35+
// WSL keeps the clipboard on the Windows side: Windows Terminal owns the selection and
36+
// the native host clipboard has no bridge to it, so this read fails unless WSLg forwards
37+
// Wayland. Read the Windows clipboard through interop instead.
38+
if (result.status === "cancelled" || !isWSL()) return undefined
39+
return readWindowsClipboard()
3640
}
3741

3842
if (result.representation.mimeType === "image/png") {
@@ -65,3 +69,39 @@ export function createClipboardAdapter(clipboard: CoreClipboardService): OwnedCl
6569
},
6670
}
6771
}
72+
73+
const WINDOWS_CLIPBOARD_IMAGE = [
74+
"Add-Type -AssemblyName System.Windows.Forms",
75+
"$image = [System.Windows.Forms.Clipboard]::GetImage()",
76+
"if (-not $image) { exit 0 }",
77+
"$stream = New-Object System.IO.MemoryStream",
78+
"$image.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png)",
79+
"[System.Convert]::ToBase64String($stream.ToArray())",
80+
].join("; ")
81+
82+
// Containers on Docker Desktop or devcontainers on Windows also run the WSL kernel but have no
83+
// interop, so detect WSL by the variables it sets instead of the kernel release.
84+
function isWSL() {
85+
return process.platform === "linux" && Boolean(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP)
86+
}
87+
88+
async function readWindowsClipboard(): Promise<ClipboardContent | undefined> {
89+
if (!Bun.which("powershell.exe")) {
90+
throw new Error("Clipboard image paste under WSL needs powershell.exe interop, which is not available")
91+
}
92+
const child = Bun.spawn(["powershell.exe", "-NonInteractive", "-NoProfile", "-Command", WINDOWS_CLIPBOARD_IMAGE], {
93+
stdin: "ignore",
94+
stdout: "pipe",
95+
stderr: "ignore",
96+
})
97+
const timeout = setTimeout(() => child.kill(), 10_000)
98+
try {
99+
const output = await new Response(child.stdout).text()
100+
if ((await child.exited) !== 0) throw new Error("Reading the Windows clipboard image failed")
101+
const data = output.trim()
102+
if (!data) return undefined
103+
return { data, mime: "image/png" }
104+
} finally {
105+
clearTimeout(timeout)
106+
}
107+
}

0 commit comments

Comments
 (0)