Skip to content

Browse CLI returns U+FFFD instead of the real text when a daemon reply splits a multibyte character #3462

Closed

Description

@gshost1

Link to a minimal reproduction

A vitest test in packages/cli, below. It uses a real unix socket as a fake daemon, so no browser and no model. Run it with cd packages/cli && pnpm exec vitest run tests/daemon-multibyte-response.test.ts.

Steps to reproduce

  1. Run browse open on a page with non-ASCII text (Japanese, for example), then a command with a large reply, such as snapshot or get text.
  2. The daemon writes the reply as one JSON line. Node reads a large reply in several chunks.
  3. If a chunk boundary falls inside a 3-byte character, the client decodes each chunk on its own.
  4. The command prints � characters where the page text was. There is no error.
import { promises as fs } from "node:fs";
import net from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { describePosix } from "./helpers/platform.js";
import { runDriverCommandViaDaemon } from "../src/lib/driver/daemon/client.js";
import { getSocketPath } from "../src/lib/driver/daemon/paths.js";

describePosix("daemon client response decoding", () => {
  let fixtureDir: string;
  let server: net.Server;

  beforeEach(async () => {
    fixtureDir = await fs.realpath(await fs.mkdtemp(join(tmpdir(), "browse-mb-")));
    const daemonDir = join(fixtureDir, "runtime");
    await fs.mkdir(daemonDir);
    vi.stubEnv("BROWSE_DAEMON_DIR", daemonDir);
  });

  afterEach(async () => {
    vi.unstubAllEnvs();
    await new Promise<void>((resolve) => (server ? server.close(() => resolve()) : resolve()));
    await fs.rm(fixtureDir, { recursive: true, force: true });
  });

  it("keeps multibyte characters that are split across socket chunks", async () => {
    const text = "日本語のテキスト".repeat(5000);
    server = net.createServer((socket) => {
      socket.once("data", (chunk) => {
        const request = JSON.parse(chunk.toString().split("\n")[0] ?? "{}");
        const payload = Buffer.from(
          `${JSON.stringify({ type: "success", id: request.id, data: { text } })}\n`,
        );
        // Large replies reach the client in several chunks. Split inside a 3-byte character
        // to make that boundary deterministic.
        const split = payload.indexOf(Buffer.from("日")) + 1;
        socket.write(payload.subarray(0, split));
        setTimeout(() => socket.end(payload.subarray(split)), 50);
      });
    });
    await new Promise<void>((resolve) => server.listen(getSocketPath("default"), resolve));

    const result = (await runDriverCommandViaDaemon("default", "snapshot" as never)) as {
      text: string;
    };
    expect(result.text).toBe(text);
  });
});

Current vs expected

Current (3 runs of 3 failed):

AssertionError: expected '\ufffd\ufffd\ufffd本語のテキスト日本語のテキスト日本語の…' to be '日本語のテキスト日本語のテキスト日本語のテキスト日本語のテキスト日本語のテ…'
 Tests  1 failed (1)

Expected: the text arrives unchanged. The first character became three �: the one byte in the first chunk and the two in the second were each decoded alone.

Why it happens

packages/cli/src/lib/driver/daemon/client.ts:218-219 (SHA 6f2686d):

socket.on("data", (chunk) => {
  buffer += chunk.toString();

chunk is a Buffer. toString() decodes it without keeping state, so a character cut at the chunk edge turns into replacement characters. JSON.parse accepts U+FFFD in a string, so nothing fails. The server side is fine: it reads through readline (daemon/server.ts), which decodes statefully.

On a real socket the cut depends on the chunk size (64 KiB for Node socket reads) and where the text lands, so it shows up only on large replies. A one-off run of the same test with a single socket.end(payload) failed in 2 of 3 runs.

Suggested fix

Let the socket decode with a stateful decoder:

     const socket = net.createConnection(socketPath);
+    // Decode with a stateful decoder: a multibyte character can be split across chunks.
+    socket.setEncoding("utf8");
     let buffer = "";
@@
-      buffer += chunk.toString();
+      buffer += chunk;

With it, the repro passes 3 of 3. In packages/cli, tests/daemon-directory.test.ts, tests/driver-foundation.test.ts and tests/driver-commands.test.ts give 90 pass / 7 fail. Clean main gives 89 pass / 7 fail, the same 7 tests (help text, absent-daemon JSON, symlink, stale lock).

Environment Information

Stagehand:

  • Language/SDK: browse CLI (packages/cli)
  • Stagehand version: [email protected] (published dist/lib/driver/daemon/client.js:162 has the same line); upstream main 6f2686d

AI Provider:

  • Provider: none (no model calls)
  • Model: none

Activity

  1. NaaeemMalik commented on Nov 16, 2026

    @NaaeemMalik

    calling chunk.toString() directly splits multibyte utf8 codepoints across socket buffers. wrapping the incoming socket stream in a StringDecoder from node:string_decoder instead of decoding each chunk on its own buffers the trailing partial bytes automatically. happy to help knock this out: https://programmingkings.com/?call&s=stagehand

  2. added a commit that references this issue on Nov 17, 2026
    0f9a64c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions