From 5f16222bac2c4e08a708e0d5f88578a1c5281968 Mon Sep 17 00:00:00 2001 From: Yshuro Date: Thu, 26 Nov 2026 18:20:31 +0100 Subject: [PATCH 1/3] fix(tui): preserve UTF-8 when copying transcript selection on WSL Signed-off-by: Yshuro --- internal/tui/transcript_selection.go | 61 ++++++++- .../transcript_selection_clipboard_test.go | 123 ++++++++++++++++++ 2 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 internal/tui/transcript_selection_clipboard_test.go diff --git a/internal/tui/transcript_selection.go b/internal/tui/transcript_selection.go index 0a6d08704..c66524fc6 100644 --- a/internal/tui/transcript_selection.go +++ b/internal/tui/transcript_selection.go @@ -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" @@ -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. @@ -1641,3 +1645,58 @@ 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 + } + encoded := powershellSetClipboardCommand(text) + cmd := exec.Command(exe, "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded) + return cmd.Run() +} + +// powershellSetClipboardCommand builds a Base64-encoded UTF-16LE PowerShell +// -EncodedCommand payload that decodes the UTF-8 text from Base64 inside +// PowerShell so no non-ASCII byte crosses the process boundary or gets +// reinterpreted through the Windows ANSI code page (e.g. clip.exe + CP932). +func powershellSetClipboardCommand(text string) string { + payloadB64 := base64.StdEncoding.EncodeToString([]byte(text)) + script := "Set-Clipboard -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" + payloadB64 + "')))" + u16 := utf16.Encode([]rune(script)) + 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) +} diff --git a/internal/tui/transcript_selection_clipboard_test.go b/internal/tui/transcript_selection_clipboard_test.go new file mode 100644 index 000000000..d276acea7 --- /dev/null +++ b/internal/tui/transcript_selection_clipboard_test.go @@ -0,0 +1,123 @@ +package tui + +import ( + "encoding/base64" + "errors" + "strings" + "testing" + "unicode/utf16" +) + +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) { + samples := []string{ + "", + "hello world", + "文字化けチェック:日本語の表示テスト", + "emoji 🚀 and quotes 'single' \"double\" $var `backtick`\nline2\tindented", + } + + for _, want := range samples { + encoded := powershellSetClipboardCommand(want) + script := decodeUTF16LEBase64(t, encoded) + + const prefix = "Set-Clipboard -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" + const suffix = "')))" + if !strings.HasPrefix(script, prefix) || !strings.HasSuffix(script, suffix) { + t.Fatalf("unexpected PowerShell script format: %q", script) + } + payloadB64 := strings.TrimSuffix(strings.TrimPrefix(script, prefix), suffix) + gotBytes, err := base64.StdEncoding.DecodeString(payloadB64) + if err != nil { + t.Fatalf("inner base64 decode failed: %v", err) + } + if string(gotBytes) != want { + t.Fatalf("round-trip mismatch: got %q, want %q", string(gotBytes), 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 + } + + if err := writeClipboard("日本語テスト"); err != nil { + t.Fatalf("writeClipboard returned error: %v", err) + } + if wslGot != "日本語テスト" { + t.Fatalf("WSL clipboard got %q, want %q", 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") + } + }) +} From aab294363762aa3d20731b4e09b85a701064074a Mon Sep 17 00:00:00 2001 From: Yshuro Date: Fri, 27 Nov 2026 11:50:15 +0100 Subject: [PATCH 2/3] fix(tui): pass WSL clipboard Base64 payload via stdin Signed-off-by: Yshuro --- internal/tui/transcript_selection.go | 28 +++++---- .../transcript_selection_clipboard_test.go | 62 ++++++++++++++----- 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/internal/tui/transcript_selection.go b/internal/tui/transcript_selection.go index c66524fc6..43c6971fe 100644 --- a/internal/tui/transcript_selection.go +++ b/internal/tui/transcript_selection.go @@ -1680,23 +1680,29 @@ func writeWSLClipboard(text string) error { if err != nil { return err } - encoded := powershellSetClipboardCommand(text) + return buildWSLClipboardCommand(exe, text).Run() +} + +func buildWSLClipboardCommand(exe, text string) *exec.Cmd { + encoded, payloadB64 := powershellSetClipboardInvocation(text) cmd := exec.Command(exe, "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded) - return cmd.Run() + cmd.Stdin = strings.NewReader(payloadB64) + return cmd } -// powershellSetClipboardCommand builds a Base64-encoded UTF-16LE PowerShell -// -EncodedCommand payload that decodes the UTF-8 text from Base64 inside -// PowerShell so no non-ASCII byte crosses the process boundary or gets -// reinterpreted through the Windows ANSI code page (e.g. clip.exe + CP932). -func powershellSetClipboardCommand(text string) string { - payloadB64 := base64.StdEncoding.EncodeToString([]byte(text)) - script := "Set-Clipboard -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" + payloadB64 + "')))" - u16 := utf16.Encode([]rune(script)) +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) + return base64.StdEncoding.EncodeToString(raw), base64.StdEncoding.EncodeToString([]byte(text)) } diff --git a/internal/tui/transcript_selection_clipboard_test.go b/internal/tui/transcript_selection_clipboard_test.go index d276acea7..26df5bfef 100644 --- a/internal/tui/transcript_selection_clipboard_test.go +++ b/internal/tui/transcript_selection_clipboard_test.go @@ -3,6 +3,7 @@ package tui import ( "encoding/base64" "errors" + "io" "strings" "testing" "unicode/utf16" @@ -25,29 +26,58 @@ func decodeUTF16LEBase64(t *testing.T, b64 string) string { } 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), } - for _, want := range samples { - encoded := powershellSetClipboardCommand(want) + 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) + } - const prefix = "Set-Clipboard -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" - const suffix = "')))" - if !strings.HasPrefix(script, prefix) || !strings.HasSuffix(script, suffix) { - t.Fatalf("unexpected PowerShell script format: %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) + } } - payloadB64 := strings.TrimSuffix(strings.TrimPrefix(script, prefix), suffix) - gotBytes, err := base64.StdEncoding.DecodeString(payloadB64) + + gotBytes, err := base64.StdEncoding.DecodeString(string(stdinBytes)) if err != nil { - t.Fatalf("inner base64 decode failed: %v", err) + t.Fatalf("stdin base64 decode failed: %v", err) } if string(gotBytes) != want { - t.Fatalf("round-trip mismatch: got %q, want %q", string(gotBytes), want) + t.Fatalf("round-trip mismatch (len=%d): got len=%d, want len=%d", len(want), len(gotBytes), len(want)) } } } @@ -74,11 +104,13 @@ func TestWriteClipboardWSLPrefersPowershellAndFallsBack(t *testing.T) { return nil } - if err := writeClipboard("日本語テスト"); err != nil { - t.Fatalf("writeClipboard returned error: %v", err) - } - if wslGot != "日本語テスト" { - t.Fatalf("WSL clipboard got %q, want %q", wslGot, "日本語テスト") + 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)) + } } }) From 570106061205f5c1b50795bf69bd2ae62dda8e8d Mon Sep 17 00:00:00 2001 From: Yshuro Date: Sun, 29 Nov 2026 14:19:53 +0100 Subject: [PATCH 3/3] test(tui): verify copyTranscriptSelectionCmd routes through WSL writer --- .../transcript_selection_clipboard_test.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/internal/tui/transcript_selection_clipboard_test.go b/internal/tui/transcript_selection_clipboard_test.go index 26df5bfef..117199118 100644 --- a/internal/tui/transcript_selection_clipboard_test.go +++ b/internal/tui/transcript_selection_clipboard_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" "unicode/utf16" + "unicode/utf8" ) func decodeUTF16LEBase64(t *testing.T, b64 string) string { @@ -153,3 +154,35 @@ func TestWriteClipboardWSLPrefersPowershellAndFallsBack(t *testing.T) { } }) } + +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) + } +}