Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(plugins): keep Chinese WSL diagnostics readable in settings (#1125)

lmliheng3a7532c2319c
diff --git a/changelog/unreleased/2026-10-15-wsl-settings-encoding.md b/changelog/unreleased/2026-10-15-wsl-settings-encoding.md
new file mode 100644
index 00000000..781d4175
--- /dev/null
+++ b/changelog/unreleased/2026-10-15-wsl-settings-encoding.md
@@ -0,0 +1,19 @@
+# Readable WSL diagnostics in settings
+
+- **Date:** 2026-10-15
+- **Type:** fix
+- **Scope:** `sandbox-wsl`
+
+[中文版](2026-10-15-wsl-settings-encoding.zh.md)
+
+Ported from upstream PenguinHarness (#1125, commit `842571de`).
+
+Settings → Plugins showed garbled Chinese wherever `wsl.exe` answered in UTF-16LE despite the
+`WSL_UTF8=1` request: the bytes were decoded as UTF-8 first, and deleting the NULs that a UTF-16
+answer then leaves cannot bring the characters back.
+
+The host now keeps `wsl.exe` output as bytes and decodes it once, at the end: UTF-16LE with or
+without a BOM is recognized (its ASCII labels, spaces and line endings still have zero high bytes,
+while UTF-8 text does not), and UTF-8 output is left as it is. The same decoder reads the
+installation logs, and live provisioning progress keeps its streaming UTF-8 decoder, so a line
+split inside a Chinese character arrives whole.
diff --git a/changelog/unreleased/2026-10-15-wsl-settings-encoding.zh.md b/changelog/unreleased/2026-10-15-wsl-settings-encoding.zh.md
new file mode 100644
index 00000000..ed9fc1d3
--- /dev/null
+++ b/changelog/unreleased/2026-10-15-wsl-settings-encoding.zh.md
@@ -0,0 +1,16 @@
+# 修复设置中的 WSL 提示乱码
+
+- **Date:** 2026-10-15
+- **Type:** fix
+- **Scope:** `sandbox-wsl`
+
+[English](2026-10-15-wsl-settings-encoding.md)
+
+移植自上游 PenguinHarness(#1125,提交 `842571de`)。
+
+「设置 → 插件」里凡是 `wsl.exe` 用 UTF-16LE 作答的地方都显示成乱码,尽管我们请求的是 `WSL_UTF8=1`:
+那些字节先被当成 UTF-8 读了一遍,而 UTF-16 的回答这样读出来只剩一堆 NUL —— 事后删掉 NUL 也拼不回原来的字。
+
+现在宿主把 `wsl.exe` 的输出**按字节留着**,到最后才解码一次:带不带 BOM 的 UTF-16LE 都认得出来(它的
+ASCII 标签、空格与换行仍有零高位字节,而 UTF-8 的文本没有),UTF-8 的输出原样保留。安装日志走同一个解码器,
+安装过程的实时进度仍用流式 UTF-8 解码器,所以一个汉字被切开的两半也能凑齐整行再交出去。
diff --git a/plugins/sandbox-wsl/src/host.ts b/plugins/sandbox-wsl/src/host.ts
index 781f45b5..11dbf060 100644
--- a/plugins/sandbox-wsl/src/host.ts
+++ b/plugins/sandbox-wsl/src/host.ts
@@ -2,13 +2,14 @@
* The Windows side: running wsl.exe, what it says about this machine, and the file this backend
* keeps about the distro it set up.
*
- * wsl.exe speaks UTF-16 by default; `WSL_UTF8=1` makes it write UTF-8, which is what every call
- * here sets. Its notices (a localhost proxy it cannot mirror into NAT mode) arrive on stderr on
- * every call and are dropped before anything reads the output.
+ * Request UTF-8 from wsl.exe, but retain its bytes: the Windows inbox executable can still
+ * return UTF-16LE diagnostics. Its notices (a localhost proxy it cannot mirror into NAT mode)
+ * arrive on stderr on every call and are dropped before anything reads the output.
*/
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
+import { StringDecoder } from "node:string_decoder";
import { isWslNotice } from "./profile.js";
/** wsl.exe by its full path: a server started with a trimmed PATH still finds it. */
@@ -31,7 +32,16 @@ export interface WslResult {
stderr: string;
}
-/** Drops WSL's own notices, and the NULs a UTF-16 answer leaves when read as UTF-8. */
+/** Decode before cleaning: deleting NULs after UTF-8 decoding cannot recover Chinese text. */
+export function decodeOutput(bytes: Buffer): string {
+ // WSL's UTF-16LE output may omit the BOM. Its ASCII labels, spaces and line endings still
+ // have zero high bytes; UTF-8 text does not. Inspect the whole answer, not one pipe chunk.
+ const utf16 =
+ (bytes[0] === 0xff && bytes[1] === 0xfe) || bytes.some((byte, i) => i % 2 === 1 && byte === 0);
+ return bytes.toString(utf16 ? "utf16le" : "utf8").replace(/^\uFEFF/, "");
+}
+
+/** Drops WSL's own notices and stray NULs from already decoded text. */
export function cleanOutput(text: string): string {
return text
.replace(/\0/g, "")
@@ -52,23 +62,24 @@ export function runWsl(
env: { ...process.env, WSL_UTF8: "1" },
stdio: ["pipe", "pipe", "pipe"],
});
- let stdout = "";
- let stderr = "";
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ // Live lines come from the Linux provisioning script, which writes UTF-8. Keep its
+ // decoder across chunks so a split multi-byte character is not replaced with U+FFFD.
+ const progress = new StringDecoder("utf8");
let partial = "";
const timer =
opts.timeoutMs !== undefined ? setTimeout(() => child.kill(), opts.timeoutMs) : undefined;
- child.stdout.setEncoding("utf8");
- child.stderr.setEncoding("utf8");
- child.stdout.on("data", (chunk: string) => {
- stdout += chunk;
+ child.stdout.on("data", (chunk: Buffer) => {
+ stdout.push(chunk);
if (opts.onLine === undefined) return;
- partial += chunk;
+ partial += progress.write(chunk);
const lines = partial.split(/\r?\n|\r/);
partial = lines.pop() ?? "";
for (const line of lines) if (line.trim() !== "") opts.onLine(line.replace(/\0/g, ""));
});
- child.stderr.on("data", (chunk: string) => {
- stderr += chunk;
+ child.stderr.on("data", (chunk: Buffer) => {
+ stderr.push(chunk);
});
child.on("error", (err) => {
if (timer) clearTimeout(timer);
@@ -76,7 +87,11 @@ export function runWsl(
});
child.on("close", (code) => {
if (timer) clearTimeout(timer);
- resolve({ code: code ?? -1, stdout: cleanOutput(stdout), stderr: cleanOutput(stderr) });
+ resolve({
+ code: code ?? -1,
+ stdout: cleanOutput(decodeOutput(Buffer.concat(stdout))),
+ stderr: cleanOutput(decodeOutput(Buffer.concat(stderr))),
+ });
});
child.stdin.end(opts.input ?? "");
});
diff --git a/plugins/sandbox-wsl/src/tasks.ts b/plugins/sandbox-wsl/src/tasks.ts
index cfa7db5e..02f885e9 100644
--- a/plugins/sandbox-wsl/src/tasks.ts
+++ b/plugins/sandbox-wsl/src/tasks.ts
@@ -10,6 +10,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import type { SandboxPolicy } from "@lmliheng/penguin-core/plugin";
import {
+ decodeOutput,
localDrives,
pathKind,
readHost,
@@ -211,10 +212,7 @@ export function elevationCommand(script: string, log: string): string {
function readText(file: string): string {
try {
- return fs
- .readFileSync(file, "utf8")
- .replace(/^\uFEFF/, "")
- .replace(/\0/g, "");
+ return decodeOutput(fs.readFileSync(file)).replace(/\0/g, "");
} catch {
return "";
}
diff --git a/plugins/sandbox-wsl/test/host.test.ts b/plugins/sandbox-wsl/test/host.test.ts
new file mode 100644
index 00000000..11cba89c
--- /dev/null
+++ b/plugins/sandbox-wsl/test/host.test.ts
@@ -0,0 +1,89 @@
+/**
+ * WSL output as the settings card and provisioning task receive it.
+ *
+ * - Given UTF-16LE Chinese diagnostics, with or without a BOM and split across byte boundaries,
+ * when WSL exits, the caller receives readable text on both stdout and stderr.
+ * - Given UTF-8 output, with or without a BOM, when WSL exits, Chinese text stays intact.
+ * - Given differently encoded stdout and stderr, when WSL exits, each is decoded independently
+ * and WSL proxy notices are removed after decoding.
+ * - Given UTF-8 provisioning progress split inside a Chinese character, when a line arrives,
+ * the callback receives the complete text before the process exits.
+ * - Given no output, when WSL exits, both result streams are empty.
+ */
+import { spawn, type ChildProcess } from "node:child_process";
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { runWsl } from "../src/host.js";
+
+vi.mock("node:child_process", () => ({ spawn: vi.fn() }));
+
+function wslProcess() {
+ const child = Object.assign(new EventEmitter(), {
+ stdin: new PassThrough(),
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ });
+ vi.mocked(spawn).mockReturnValueOnce(child as unknown as ChildProcess);
+ return child;
+}
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("WSL output", () => {
+ it.each([false, true])("preserves split UTF-16LE Chinese diagnostics (BOM: %s)", async (bom) => {
+ const child = wslProcess();
+ const result = runWsl(["--version"]);
+ const message = "未安装适用于 Linux 的 Windows 子系统。请运行 wsl.exe --install。";
+ const bytes = Buffer.from(`${bom ? "\uFEFF" : ""}${message}\r\n`, "utf16le");
+ for (const byte of bytes) {
+ child.stdout.write(Buffer.from([byte]));
+ child.stderr.write(Buffer.from([byte]));
+ }
+ child.emit("close", 1);
+ expect(await result).toEqual({ code: 1, stdout: message, stderr: message });
+ });
+
+ it.each([false, true])("preserves UTF-8 Chinese output (BOM: %s)", async (bom) => {
+ const child = wslProcess();
+ const result = runWsl(["--list", "--quiet"]);
+ child.stdout.write(Buffer.from(`${bom ? "\uFEFF" : ""}开发环境\r\nUbuntu\r\n`));
+ child.emit("close", 0);
+ expect(await result).toEqual({ code: 0, stdout: "开发环境\nUbuntu", stderr: "" });
+ });
+
+ it("decodes each stream independently and filters decoded WSL notices", async () => {
+ const child = wslProcess();
+ const result = runWsl(["--version"]);
+ child.stdout.write(Buffer.from("WSL 版本: 2.7.14.0\r\n"));
+ child.stderr.write(
+ Buffer.from("wsl: 检测到 localhost 代理配置\r\n需要重新启动 Windows。\r\n", "utf16le"),
+ );
+ child.emit("close", 0);
+ expect(await result).toEqual({
+ code: 0,
+ stdout: "WSL 版本: 2.7.14.0",
+ stderr: "需要重新启动 Windows。",
+ });
+ });
+
+ it("delivers complete UTF-8 provisioning lines before the process exits", async () => {
+ const child = wslProcess();
+ const onLine = vi.fn();
+ const result = runWsl(["--exec", "/bin/sh", "-s"], { onLine });
+ const bytes = Buffer.from("正在安装软件包\r\n");
+ child.stdout.write(bytes.subarray(0, 2));
+ expect(onLine).not.toHaveBeenCalled();
+ child.stdout.write(bytes.subarray(2));
+ expect(onLine).toHaveBeenCalledExactlyOnceWith("正在安装软件包");
+ child.emit("close", 0);
+ expect((await result).stdout).toBe("正在安装软件包");
+ });
+
+ it("returns empty streams when WSL writes nothing", async () => {
+ const child = wslProcess();
+ const result = runWsl(["--terminate", "penguin-sandbox"]);
+ child.emit("close", 0);
+ expect(await result).toEqual({ code: 0, stdout: "", stderr: "" });
+ });
+});