From 6db416cd47906efbaa11103bd7cedf4d7d5dfd26 Mon Sep 17 00:00:00 2001 From: VIOLETee0 <1842771550@qq.com> Date: Fri, 27 Nov 2026 09:00:47 +0800 Subject: [PATCH] Preserve UTF-8 across terminal output chunks --- .../__tests__/terminal-output-utf8.test.ts | 96 +++++++++++++++++++ sdk/src/tools/run-terminal-command.ts | 28 ++++-- 2 files changed, 118 insertions(+), 6 deletions(-) create mode 100644 sdk/src/__tests__/terminal-output-utf8.test.ts diff --git a/sdk/src/__tests__/terminal-output-utf8.test.ts b/sdk/src/__tests__/terminal-output-utf8.test.ts new file mode 100644 index 0000000000..ddabb2a374 --- /dev/null +++ b/sdk/src/__tests__/terminal-output-utf8.test.ts @@ -0,0 +1,96 @@ +import { expect, it } from 'bun:test' +import { readFileSync, rmSync } from 'fs' +import { tmpdir } from 'os' +import path from 'path' +import { PassThrough } from 'stream' +import { finished } from 'stream/promises' + +import { runTerminalCommand } from '../tools/run-terminal-command' + +import type { TerminalCommandBroker } from '../tools/run-terminal-command' + +// Use real streams to split multibyte characters without depending on pipe timing. +it('preserves split UTF-8 in foreground output and brokered background logs', async () => { + const collected: { stdout: string; stderr: string }[] = [] + for (const process_type of ['SYNC', 'BACKGROUND'] as const) { + const stdout = new PassThrough() + const stderr = new PassThrough() + const brokerChunks: unknown[] = [] + stdout.on('data', (chunk) => brokerChunks.push(chunk)) + let finish!: (code: number) => void + let logDirectory: string | undefined + const terminalCommandBroker: TerminalCommandBroker = { + ownsShell: true, + start: () => ({ + pid: 987_654_320, + stdout, + stderr, + completion: new Promise((resolve) => { + finish = resolve + }), + kill: () => {}, + isAlive: () => false, + }), + } + const run = runTerminalCommand({ + command: 'UTF-8 stream fixture', + process_type, + cwd: process.cwd(), + timeout_seconds: 5, + terminalCommandBroker, + }) + try { + // Keep stdout/stderr decoder state independent; leave ANSI codes intact. + const output = Buffer.from('Aé中🙂Z') + const error = Buffer.from('ß错🚀') + stdout.write('\x1b[31m') + for ( + let index = 0; + index < Math.max(output.length, error.length); + index++ + ) { + if (index < output.length) + stdout.write(output.subarray(index, index + 1)) + if (index < error.length) stderr.write(error.subarray(index, index + 1)) + } + stdout.write('\x1b[0m') + stdout.end(Buffer.from([0xe4])) + stderr.end(Buffer.from([0xf0])) + await Promise.all([finished(stdout), finished(stderr)]) + finish(0) + const [{ value }] = await run + if ('stdoutPath' in value && value.stdoutPath && value.stderrPath) { + logDirectory = path.dirname(value.stdoutPath) + collected.push({ + stdout: readFileSync(value.stdoutPath, 'utf8'), + stderr: readFileSync(value.stderrPath, 'utf8'), + }) + } else if ('stdout' in value) { + collected.push({ + stdout: value.stdout ?? '', + stderr: value.stderr ?? '', + }) + } + expect(brokerChunks.every(Buffer.isBuffer)).toBe(true) + } finally { + finish(0) + await run + stdout.destroy() + stderr.destroy() + if (logDirectory) { + if ( + path.dirname(logDirectory) !== path.resolve(tmpdir()) || + !path.basename(logDirectory).startsWith('codebuff-process-') + ) { + throw new Error('Unexpected background log directory') + } + rmSync(logDirectory, { recursive: true, force: true }) + } + } + } + // An incomplete sequence at EOF still produces the usual replacement character. + expect(collected).toEqual([ + { stdout: 'Aé中🙂Z�', stderr: 'ß错🚀�' }, + { stdout: 'Aé中🙂Z�', stderr: 'ß错🚀�' }, + ]) +}) diff --git a/sdk/src/tools/run-terminal-command.ts b/sdk/src/tools/run-terminal-command.ts index de59c5884f..880f4d0080 100644 --- a/sdk/src/tools/run-terminal-command.ts +++ b/sdk/src/tools/run-terminal-command.ts @@ -1,6 +1,7 @@ import { spawn, spawnSync } from 'child_process' import { closeSync, mkdtempSync, openSync, statSync, writeFileSync } from 'fs' import { Readable as NodeReadable } from 'stream' +import { StringDecoder } from 'string_decoder' import * as os from 'os' import * as path from 'path' @@ -144,6 +145,21 @@ export class BoundedOutputBuffer { } } +// Keep broker streams in their original encoding for any other consumers. +function collectDecodedOutput( + stream: Readable, + onText: (text: string) => void, +): void { + const decoder = new StringDecoder('utf8') + const append = (text: string) => { + if (text) onText(text) + } + stream.on('data', (data: Buffer | string) => { + append(typeof data === 'string' ? data : decoder.write(data)) + }) + stream.once('end', () => append(decoder.end())) +} + function killProcessGroup(child: ChildProcess, signal: NodeJS.Signals) { if (os.platform() === 'win32' && child.pid) { // Node's child.kill() only terminates the direct process on Windows. Since @@ -584,13 +600,13 @@ export function runTerminalCommand({ } // Collect stdout - childProcess.stdout.on('data', (data: Buffer) => { - stdout.append(data.toString()) + collectDecodedOutput(childProcess.stdout, (data) => { + stdout.append(data) }) // Collect stderr - childProcess.stderr.on('data', (data: Buffer) => { - stderr.append(data.toString()) + collectDecodedOutput(childProcess.stderr, (data) => { + stderr.append(data) }) // Handle process completion @@ -730,8 +746,8 @@ async function startBackgroundCommand( [child.stderr, stderrPath], ] as const) { const output = new BoundedOutputBuffer(COMMAND_OUTPUT_LIMIT) - stream.on('data', (data: Buffer) => { - output.append(data.toString()) + collectDecodedOutput(stream, (data) => { + output.append(data) try { writeFileSync(file, output.format()) } catch {