Skip to content

bug(core): shell completion tail splits UTF-8 characters at the byte limit #55707

Closed

Description

@HootRock

Description

The bounded shell completion can start in the middle of a valid UTF-8 character. The saved output and persisted shell history are correct, but the completion passed into model messages gains U+FFFD characters.

In packages/core/src/shell.ts, result() requests the last maxBytes bytes, then output() independently decodes that slice with toString("utf8"). With the default 51,200-byte limit, 300,000 bytes of 中 produce two replacement characters at the beginning of the tail. The decoded tail is 51,204 bytes.

Please preserve complete UTF-8 characters in the bounded completion. The public byte-cursor paging contract may need separate treatment. This predates the legacy-history cap in #54556 and differs from the stdout/stderr interleaving in #36665.

Plugins

No third-party plugins; offline test fixtures.

OpenCode version

Tested source 8799179; shell.ts is identical after line-ending normalization at dev 4397ee4.

Steps to reproduce

Using the existing offline Session test harness:

  1. Invoke Session.shell({ sessionID, command: 'node -e "process.stdout.write(\'\\u4E2D\'.repeat(100000))"' }).
  2. Read Session.messages(), the spool file named in the completion, and Session.inbox().
  3. The first two contain exactly 100,000 中 characters; the synthetic completion contains two U+FFFD characters. Actual toLLMMessages() forwards that completion unchanged.

Additional real subprocess cases: appending a to that CJK output gives one replacement; 75,001 emoji followed by a gives three. ASCII, aligned CJK, and aligned emoji controls give zero. All six preserve their full spool bytes and stored history.

The six observation checks pass; changing their expectation to no introduced replacement gives three passes and three failures. AI-assisted native Windows investigation with Bun 1.4.2, Node 24.13.0 and an existing Effect 4.0.1 dependency runtime. No live provider, TUI interaction, full suite, or fresh current-dev dependency build was tested.

Screenshot and/or share link

Headless service-level reproduction; no screenshot or shared session.

Operating System

Windows 11

Terminal

Headless Bun test runner

Activity

  1. opencode-agent commented on Oct 15, 2026

    @opencode-agent
    Contributor

    Thanks for the detailed report. I reproduced this on the latest dev (4397ee4) using the offline Session harness with a real node -e subprocess and the default 51,200-byte limit.

    • 100,000 × 中: the stored shell history has no U+FFFD, but the synthetic completion in Session.inbox() starts with 2 of them (\n��中中…).
    • 100,000 × 中 + a: 1 U+FFFD in the completion.
    • 75,001 × 😀 + a: 3 U+FFFD in the completion.
    • 300,000 ASCII bytes (control): none.

    The cause matches what you found: Shell.result in packages/core/src/shell.ts requests the tail from size - maxBytes, and output() decodes that byte slice directly, so the tail can start partway through a character. The test file below reproduces it; place it in packages/core/test/ to run it.

    Reproduction script (issue-55707.test.ts)
    import { describe, expect, setDefaultTimeout } from "bun:test"
    import fs from "fs/promises"
    import path from "path"
    import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Option, Schedule, Stream } from "effect"
    import { Bus } from "@opencode/core/bus"
    import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
    import { Location } from "@opencode/core/location"
    import { LocationServiceMap } from "@opencode/core/location-service-map"
    import { AbsolutePath } from "@opencode/core/schema"
    import { Session } from "@opencode/core/session"
    import { SessionEvent } from "@opencode/core/session/event"
    import { SessionExecution } from "@opencode/core/session/execution"
    import { SessionRunCoordinator } from "@opencode/core/session/run-coordinator"
    import { Shell } from "@opencode/core/shell"
    import { LayerNode } from "@opencode/util/effect/layer-node"
    import { location } from "./fixture/location"
    import { offlineModels } from "./fixture/models"
    import { tmpdirScoped } from "./fixture/tmpdir"
    import { testEffect } from "./lib/effect"
    
    // Every test boots a real Location, so shell start waits for cold plugin activation before spawning.
    setDefaultTimeout(15_000)
    
    class ExecutionControl extends Context.Service<
      ExecutionControl,
      {
        started: Deferred.Deferred<void>
        release: Deferred.Deferred<void>
        wakes: Session.ID[]
      }
    >()("test/SessionShell/ExecutionControl") {}
    
    const controlLayer = Layer.effect(
      ExecutionControl,
      Effect.gen(function* () {
        return { started: yield* Deferred.make<void>(), release: yield* Deferred.make<void>(), wakes: [] }
      }),
    )
    
    const executionLayer = Layer.effect(
      SessionExecution.Service,
      Effect.gen(function* () {
        const control = yield* ExecutionControl
        const coordinator = yield* SessionRunCoordinator.make<Session.ID, never>({
          drain: () => Deferred.succeed(control.started, undefined).pipe(Effect.andThen(Deferred.await(control.release))),
        })
        return SessionExecution.Service.of({
          active: coordinator.active,
          isActive: coordinator.isActive,
          resume: coordinator.run,
          interrupt: (sessionID) => coordinator.interrupt(sessionID),
          awaitIdle: coordinator.awaitIdle,
          wake: (sessionID) =>
            Effect.sync(() => control.wakes.push(sessionID)).pipe(Effect.andThen(coordinator.wake(sessionID))),
        })
      }),
    )
    
    const it = testEffect(
      AppNodeBuilder.build(LayerNode.group([Bus.node, Session.node, SessionExecution.node, LocationServiceMap.node]), [
        Bus.node.replace(Bus.configured({ persist: true })),
        SessionExecution.node.replace(executionLayer.pipe(Layer.provide(controlLayer))),
        offlineModels,
      ]).pipe(Layer.provideMerge(controlLayer)),
    )
    
    const setup = Effect.gen(function* () {
      const tmp = yield* tmpdirScoped()
      const session = yield* Session.Service
      const created = yield* session.create({ location: Location.Ref.make({ directory: AbsolutePath.make(tmp.path) }) })
      const locations = yield* LocationServiceMap.Service
      const shell = yield* Shell.Service.pipe(Effect.provide(locations.get(created.location)))
      const control = yield* ExecutionControl
      const execution = yield* SessionExecution.Service
      return { tmp, session, created, shell, control, execution }
    })
    
    const log = (session: Session.Interface, sessionID: Session.ID, follow = false) =>
      session.log({ sessionID, follow }).pipe(Stream.filter((event) => !Bus.isSynced(event)))
    
    // Repro for anomalyco/opencode#55707: bounded shell completion tail splits UTF-8 characters.
    const cases = [
      { name: "100000 x 中 (unaligned tail)", js: "process.stdout.write('\\u4E2D'.repeat(100000))" },
      { name: "100000 x 中 + a", js: "process.stdout.write('\\u4E2D'.repeat(100000)+'a')" },
      { name: "75001 x 😀 + a", js: "process.stdout.write('\\u{1F600}'.repeat(75001)+'a')" },
      { name: "ascii control", js: "process.stdout.write('x'.repeat(300000))" },
    ]
    
    describe("issue 55707", () => {
      for (const c of cases) {
        it.live(c.name, () =>
          Effect.gen(function* () {
            const fixture = yield* setup
            const command = `node -e "${c.js}"`
            yield* fixture.session.shell({ sessionID: fixture.created.id, command })
            const messages = yield* fixture.session.messages({ sessionID: fixture.created.id })
            const message = messages[0]
            if (message?.type !== "shell") return yield* Effect.die("no shell message")
            const inbox = yield* fixture.session.inbox(fixture.created.id)
            const completion = inbox[0]
            if (completion?.type !== "synthetic") return yield* Effect.die("no completion")
            const text = completion.payload.text
            const fffd = (s: string) => (s.match(/\uFFFD/g) ?? []).length
            console.log(`[${c.name}] stored-history U+FFFD=${fffd(message.output?.output ?? "")} completion U+FFFD=${fffd(text)} completion-head=${JSON.stringify(text.slice(text.indexOf("\uFFFD") - 5, text.indexOf("\uFFFD") + 5))}`)
            expect(fffd(text)).toBe(0)
          }),
        )
      }
    })

    Run it: bun issue-55707.test.ts

  2. neriousy commented on Nov 19, 2026

    @neriousy
    Member

    Fixed by #63967 and #63984, which keep the bounded shell output tail and output pages from splitting UTF-8 characters. If you still see this on the latest version, comment here and we'll reopen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions