Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 66 additions & 1 deletion internal/tui/transcript_selection.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package tui

import (
"encoding/base64"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"time"
"unicode/utf16"
"unicode/utf8"

tea "charm.land/bubbletea/v2"
Expand Down Expand Up @@ -1631,7 +1635,7 @@ func copyTranscriptSelectionCmd(text string) tea.Cmd {
// at all — so the auto-copy-on-select actually lands on the clipboard. Fall
// back to OSC52 (forwarded by the terminal) for remote/SSH sessions where no
// local clipboard utility is reachable.
if err := clipboard.WriteAll(text); err != nil {
if err := writeClipboard(text); err != nil {
if _, oscErr := os.Stdout.WriteString(ansi.SetSystemClipboard(text)); oscErr != nil {
// Both paths failed; report it rather than claiming a copy that
// never reached any clipboard.
Expand All @@ -1641,3 +1645,64 @@ func copyTranscriptSelectionCmd(text string) tea.Cmd {
return transcriptCopiedMsg{chars: utf8.RuneCountInString(text)}
}
}

var (
isWSLFunc = detectWSL
writeWSLFunc = writeWSLClipboard
clipboardWriteAll = clipboard.WriteAll
)

func writeClipboard(text string) error {
if isWSLFunc() {
if err := writeWSLFunc(text); err == nil {
return nil
}
}
return clipboardWriteAll(text)
}

func detectWSL() bool {
if runtime.GOOS != "linux" {
return false
}
if os.Getenv("WSL_DISTRO_NAME") != "" {
return true
}
data, err := os.ReadFile("/proc/version")
if err != nil {
return false
}
return strings.Contains(strings.ToLower(string(data)), "microsoft")
}

func writeWSLClipboard(text string) error {
exe, err := exec.LookPath("powershell.exe")
if err != nil {
return err
}
return buildWSLClipboardCommand(exe, text).Run()
}

func buildWSLClipboardCommand(exe, text string) *exec.Cmd {
encoded, payloadB64 := powershellSetClipboardInvocation(text)
cmd := exec.Command(exe, "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
cmd.Stdin = strings.NewReader(payloadB64)
return cmd
}

const powershellSetClipboardScript = "Set-Clipboard -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String([Console]::In.ReadToEnd())))"

// powershellSetClipboardInvocation returns a fixed-size UTF-16LE Base64
// -EncodedCommand script and an ASCII Base64 stdin payload for text. Sending
// the payload via stdin avoids the Windows 32,767-character command-line limit
// on large selections while keeping non-ASCII bytes out of the Windows ANSI
// code page (e.g. clip.exe + CP932).
func powershellSetClipboardInvocation(text string) (encodedCmd, stdinPayload string) {
u16 := utf16.Encode([]rune(powershellSetClipboardScript))
raw := make([]byte, len(u16)*2)
for i, v := range u16 {
raw[i*2] = byte(v)
raw[i*2+1] = byte(v >> 8)
}
return base64.StdEncoding.EncodeToString(raw), base64.StdEncoding.EncodeToString([]byte(text))
}
188 changes: 188 additions & 0 deletions internal/tui/transcript_selection_clipboard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package tui

import (
"encoding/base64"
"errors"
"io"
"strings"
"testing"
"unicode/utf16"
"unicode/utf8"
)

func decodeUTF16LEBase64(t *testing.T, b64 string) string {
t.Helper()
raw, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
t.Fatalf("DecodeString failed: %v", err)
}
if len(raw)%2 != 0 {
t.Fatalf("expected even byte length for UTF-16LE, got %d", len(raw))
}
u16 := make([]uint16, len(raw)/2)
for i := range u16 {
u16[i] = uint16(raw[i*2]) | uint16(raw[i*2+1])<<8
}
return string(utf16.Decode(u16))
}

func TestPowershellSetClipboardCommandRoundTrip(t *testing.T) {
// Windows CreateProcessW limits the full command line to 32,767 characters.
// 8,192 multi-byte Japanese runes would exceed that limit if embedded in
// -EncodedCommand, so the command line must stay fixed-size and pass the
// Base64 payload over stdin.
const windowsMaxCommandLine = 32767

samples := []string{
"",
"hello world",
"文字化けチェック:日本語の表示テスト",
"emoji 🚀 and quotes 'single' \"double\" $var `backtick`\nline2\tindented",
strings.Repeat("日", 8192),
}

var fixedEncoded string
for i, want := range samples {
cmd := buildWSLClipboardCommand("powershell.exe", want)
if len(cmd.Args) != 5 || cmd.Args[1] != "-NoProfile" || cmd.Args[2] != "-NonInteractive" || cmd.Args[3] != "-EncodedCommand" {
t.Fatalf("unexpected PowerShell args: %q", cmd.Args)
}
if cmdLineLen := len(strings.Join(cmd.Args, " ")); cmdLineLen >= windowsMaxCommandLine {
t.Fatalf("sample %d command line length %d exceeds Windows limit %d", i, cmdLineLen, windowsMaxCommandLine)
}

encoded := cmd.Args[4]
if i == 0 {
fixedEncoded = encoded
} else if encoded != fixedEncoded {
t.Fatalf("sample %d changed -EncodedCommand; want fixed-size command", i)
}

script := decodeUTF16LEBase64(t, encoded)
if script != powershellSetClipboardScript {
t.Fatalf("unexpected PowerShell script: %q", script)
}

stdinBytes, err := io.ReadAll(cmd.Stdin)
if err != nil {
t.Fatalf("reading cmd.Stdin failed: %v", err)
}
for _, b := range stdinBytes {
if b > 0x7f {
t.Fatalf("non-ASCII byte 0x%02x in stdin payload", b)
}
}

gotBytes, err := base64.StdEncoding.DecodeString(string(stdinBytes))
if err != nil {
t.Fatalf("stdin base64 decode failed: %v", err)
}
if string(gotBytes) != want {
t.Fatalf("round-trip mismatch (len=%d): got len=%d, want len=%d", len(want), len(gotBytes), len(want))
}
}
}

func TestWriteClipboardWSLPrefersPowershellAndFallsBack(t *testing.T) {
origIsWSL := isWSLFunc
origWriteWSL := writeWSLFunc
origWriteAll := clipboardWriteAll
t.Cleanup(func() {
isWSLFunc = origIsWSL
writeWSLFunc = origWriteWSL
clipboardWriteAll = origWriteAll
})

t.Run("WSL success skips atotto/clipboard", func(t *testing.T) {
isWSLFunc = func() bool { return true }
var wslGot string
writeWSLFunc = func(text string) error {
wslGot = text
return nil
}
clipboardWriteAll = func(string) error {
t.Fatal("clipboardWriteAll should not be called when WSL clipboard succeeds")
return nil
}

for _, sample := range []string{"日本語テスト", strings.Repeat("日", 8192)} {
if err := writeClipboard(sample); err != nil {
t.Fatalf("writeClipboard returned error: %v", err)
}
if wslGot != sample {
t.Fatalf("WSL clipboard mismatch (len=%d): got len=%d", len(sample), len(wslGot))
}
}
})

t.Run("WSL failure falls back to atotto/clipboard", func(t *testing.T) {
isWSLFunc = func() bool { return true }
writeWSLFunc = func(string) error {
return errors.New("powershell.exe not found")
}
var fallbackGot string
clipboardWriteAll = func(text string) error {
fallbackGot = text
return nil
}

if err := writeClipboard("fallback text"); err != nil {
t.Fatalf("writeClipboard returned error: %v", err)
}
if fallbackGot != "fallback text" {
t.Fatalf("fallback clipboard got %q, want %q", fallbackGot, "fallback text")
}
})

t.Run("non-WSL uses atotto/clipboard directly", func(t *testing.T) {
isWSLFunc = func() bool { return false }
writeWSLFunc = func(string) error {
t.Fatal("writeWSLFunc should not be called outside WSL")
return nil
}
var got string
clipboardWriteAll = func(text string) error {
got = text
return nil
}

if err := writeClipboard("native text"); err != nil {
t.Fatalf("writeClipboard returned error: %v", err)
}
if got != "native text" {
t.Fatalf("native clipboard got %q, want %q", got, "native text")
}
})
}

func TestCopyTranscriptSelectionCmdUsesWSLWriter(t *testing.T) {
origIsWSL := isWSLFunc
origWriteWSL := writeWSLFunc
origWriteAll := clipboardWriteAll
t.Cleanup(func() {
isWSLFunc = origIsWSL
writeWSLFunc = origWriteWSL
clipboardWriteAll = origWriteAll
})

isWSLFunc = func() bool { return true }
var wslGot string
writeWSLFunc = func(text string) error {
wslGot = text
return nil
}
clipboardWriteAll = func(string) error {
t.Fatal("clipboardWriteAll should not be called when WSL clipboard succeeds")
return nil
}

const selection = "文字化けチェック:日本語 🚀"
msg := copyTranscriptSelectionCmd(selection)()
if wslGot != selection {
t.Fatalf("WSL writer got %q, want %q", wslGot, selection)
}
wantMsg := transcriptCopiedMsg{chars: utf8.RuneCountInString(selection)}
if msg != wantMsg {
t.Fatalf("copyTranscriptSelectionCmd() = %#v, want %#v", msg, wantMsg)
}
}
Loading