Skip to content

acp: directory paths cause failing file reads over Zed remote worktree #52952

Open

Description

@Francis13CR

Summary

When opencode runs as an ACP agent server inside Zed connected to a remote (SSH/devcontainer) worktree, the session produces a stream of failing file reads for paths that are directories (/var/www, /var/www/app/css, /var/www/app/js), and Zed's remote server ends up restarting. The root cause appears to be on the Zed side (zed-industries/zed#48240), so this issue is for tracking/coordination and to check whether opencode can guard the pattern.

Environment

  • opencode: v2.0.18, ACP mode (opencode acp)
  • Client: Zed 1.22.0+stable.364 (remote devcontainer over SSH), host Ubuntu 24.04
  • Plugin: superpowers@git+https://github.com/obra/superpowers.git

What happens

  • Zed's Zed.log records, repeatedly:
    • ERROR [acp_thread] RPC request OpenBufferByPath failed: Binary files are not supported
    • ERROR [acp_thread] no worktree found for id N (dozens of times)
  • Zed's remote server log records type:OpenBufferByPath, error:reading bytes of the file "/var/www" (the worktree directory), plus /var/www/app/css and /var/www/app/js (also directories), and 42× Binary files are not supported.
  • The remote server restarts ~9× (stdin read failed: unexpected end of file), which invalidates worktree IDs, after which the no worktree found for id N churn begins.
  • User-visible symptoms: UI actions stop responding, the input caret blinks very fast, panels render blank, and opening a file takes ~30 s.

Expected

  • Failed ACP file-access requests on directory paths should not cascade into repeated reads, and worktree-id invalidation after a remote-server restart should not cause a retry storm.

Actual

  • Repeated failing reads and retries; the client becomes unresponsive during the episode.

Additional Context

Activity

  1. github-actions commented on Oct 3, 2026

    @github-actions
    Contributor

    This issue might be a duplicate of existing issues. Please check:

    • #33510: Zed logs file-read errors when OpenCode sends directory paths as ACP ToolCallLocations, matching the directory-read symptom here.
  2. Francis13CR commented on Oct 3, 2026

    @Francis13CR
    Author

    Source-level follow-up: which side produces the directory paths

    Following the trace, the failing OpenBufferByPath calls come from Zed's ACP tool-call location resolution: crates/acp_thread/src/acp_thread.rs — ToolCall::resolve_location calls project.open_buffer(path) for every ToolCallLocation the agent attaches to a tool call (acp_thread.rs:1262-1281; resolve_locations invoked at 3466/3552/3621).

    So the Zed-side bug is that it tries to open a directory path as a buffer. From the opencode side, the relevant detail is that our tools' reported locations can be directories, e.g. the worktree root /var/www, /var/www/app/css, /var/www/app/js (all directories), which is what triggers it.

    If opencode emits ToolCallLocation entries from list/glob/grep-style operations, it would help to:

    • only emit file paths in tool-call locations (skip directories), or
    • omit locations entirely for operations whose target is a directory.

    This is only a defensive improvement — the primary fix belongs in Zed (zed-industries/zed#48240). Cross-referencing so both sides have the mechanism.

  3. Francis13CR commented on Oct 3, 2026

    @Francis13CR
    Author

    Thanks. Re #33510: that issue was auto-closed by the inactivity bot ("automatically closed after 60 days of no activity… if the issue is still relevant please open a new one"), not fixed. This is that re-report: the problem is still present and reproducible on v2.0.18.

    I traced it to the current code. packages/opencode/src/acp/tool.ts toLocations still returns directory paths:

    export function toLocations(toolName: string, input: ToolInput, cwd?: string): ToolCallLocation[] {
      const tool = toolName.toLocaleLowerCase()
    
      switch (tool) {
        case "bash":
        case "shell": {
          const workdir = shellWorkdir(input, cwd)
          return workdir ? [{ path: workdir }] : []   // <-- workdir is a DIRECTORY
        }
    
        case "read":
        case "edit":
        case "write":
          return locationFrom(input.filePath ?? input.filepath)
    
        case "external_directory":
          return locationFrom(input.filePath ?? input.filepath, input.parentDir, input.directories)
    
        case "grep":
        case "glob":
        case "context":
        case "context7_resolve_library_id":
        case "context7_get_library_docs":
          return locationFrom(input.path)             // <-- input.path is a search ROOT (directory)
    
        default:
          return []
      }
    }

    That maps exactly to what Zed logs in my session over a remote worktree at /var/www:

    • bash/shell → reading bytes of the file "/var/www" (the shell workdir) — 164×
    • grep/glob → reading bytes of the file "/var/www/app/js" and "/var/www/app/css" (search roots)
    • plus Binary files are not supported

    Zed then calls open_buffer on each location and logs the failure for every tool-call update. On a remote connection this also destabilizes the client: remote-server restarts, no worktree found for id N, and received chunk for buffer ... without initial state.

    packages/opencode/test/acp/tool.test.ts only covers read/edit, so nothing guards the directory cases.

    Suggested fix (same as originally proposed in #33510):

    1. Drop the bash/shell workdir location — it's already available via rawInput.cwd.
    2. For grep/glob/context, only emit a location when the resolved path is a file, not a directory.
    3. Add tests asserting that toLocations never returns directory paths for bash/grep/glob.

    The Zed-side counterpart is zed-industries/zed#48240 (Zed should also refuse to open_buffer a directory).

  4. Francis13CR commented on Oct 3, 2026

    @Francis13CR
    Author

    Related observation: in-flight turns marked interrupted when the ACP server restarts

    Separate from the directory-location issue, but observed in the same session — recording it here since it's the ACP/session surface.

    When the ACP server restarts/reconnects (Zed window reload, or the remote connection dropping), an in-flight turn is recorded as idle with outcome=interrupted, and the client surfaces it as canceled/empty — i.e. it looks like the user aborted it.

    Evidence from the container-side store (session_message, type idle): {"outcome":"interrupted"} at the exact moment the server logged watcher stopped for all watched paths plus InterruptError: All fibers interrupted without error on /api/event, right before a new server run started. The corresponding session_v2.idle_outcome was interrupted.

    This may be expected behavior on a client reconnect rather than a bug, but a distinct "connection lost / canceled by disconnect" state would avoid the turn looking like a user cancellation. Downstream of zed-industries/zed#48240 (remote client instability causing the reconnects).

  5. opencodejr commented on Oct 27, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report and the Zed cross-reference. I could reproduce the opencode side of this on v2.0.18, and it still happens on the latest dev (45b53fe).

    What I did:

    • Ran opencode acp with a minimal ACP client over stdio and a mock model that makes one shell call (ls, no workdir) and one grep call on a subdirectory.
    • Logged the locations that opencode sends in tool_call / tool_call_update.

    In both versions, the project directory (for shell) and the grep directory come back as tool-call locations, and they are sent again on the in-progress and completed updates. Zed opens a buffer for each location. On a remote worktree that is exactly the failing reading bytes of the file "/var/www" / Binary files are not supported read in your logs, so opencode makes the Zed-side problem (zed-industries/zed#48240) worse. I couldn't run Zed here, so I didn't see the remote-server restarts or the retry storm themselves.

    The script below reproduces it. #52956 fixed the same thing for v1 (it reported only file locations) but was never merged, so the fix still needs to be done in v2. I've passed this on to the maintainers.

    Reproduction script (acp-e2e.ts)
    // End-to-end reproduction of anomalyco/opencode#52952 over the real ACP stdio protocol.
    // A mock OpenAI-compatible server makes the model call `bash` (no workdir) and
    // `grep` on a directory; an ACP client logs every tool_call location opencode sends
    // and flags the ones that are directories (Zed opens a buffer for each one).
    //
    // Run: bun acp-e2e.ts            (uses `opencode` on PATH)
    //      From a source checkout:
    //      BUN_OPTIONS="--conditions=browser --preload=$REPO/packages/tui/node_modules/@opentui/solid/scripts/preload.js" \
    //        OC_CMD="bun $REPO/packages/cli/src/index.ts" bun acp-e2e.ts
    import { mkdtempSync, mkdirSync, writeFileSync, statSync } from "node:fs"
    import { tmpdir } from "node:os"
    import { join } from "node:path"
    
    const project = mkdtempSync(join(tmpdir(), "acp52952-"))
    mkdirSync(join(project, "app/css"), { recursive: true })
    writeFileSync(join(project, "app/css/site.css"), "body{}\n")
    
    let toolTurn = 0
    const sse = (chunks: any[]) =>
      new Response(chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n", {
        headers: { "content-type": "text/event-stream" },
      })
    const chunk = (delta: any, finish: string | null = null) => ({
      id: "c", object: "chat.completion.chunk", created: 0, model: "mock",
      choices: [{ index: 0, delta, finish_reason: finish }],
    })
    const server = Bun.serve({
      port: 0,
      async fetch(req) {
        const url = new URL(req.url)
        if (url.pathname.endsWith("/models")) return Response.json({ data: [{ id: "mock", object: "model" }] })
        const body: any = await req.json().catch(() => ({}))
        console.error("mock hit", url.pathname, (body.tools ?? []).map((t: any) => t.function?.name ?? t.name).join(","))
        const hasTools = Array.isArray(body.tools) && body.tools.length > 0
        if (hasTools && toolTurn === 0) {
          toolTurn++
          const names = body.tools.map((t: any) => t.function?.name)
          const calls = [
            { name: names.find((n: string) => n === "bash" || n === "shell") ?? "bash", args: { command: "ls", description: "list" } },
            { name: names.find((n: string) => n === "grep") ?? "grep", args: { pattern: "body", path: join(project, "app/css") } },
          ]
          return sse([
            chunk({ role: "assistant", tool_calls: calls.map((c, i) => ({ index: i, id: `call_${i}`, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } })) }),
            chunk({}, "tool_calls"),
          ])
        }
        return sse([chunk({ role: "assistant", content: "done" }), chunk({}, "stop")])
      },
    })
    
    writeFileSync(join(project, "opencode.json"), JSON.stringify({
      $schema: "https://opencode.ai/config.json",
      model: "mock/mock", small_model: "mock/mock",
      permission: { "*": "allow" },
      provider: { mock: { npm: "@ai-sdk/openai-compatible", name: "Mock", options: { baseURL: `http://127.0.0.1:${server.port}/v1`, apiKey: "x" }, models: { mock: { name: "mock", tool_call: true } } } },
    }))
    
    const cmd = (process.env.OC_CMD ?? "opencode").split(" ")
    const proc = Bun.spawn([...cmd, "acp"], { cwd: project, stdin: "pipe", stdout: "pipe", stderr: "inherit",
      env: { ...process.env, OPENCODE_DISABLE_AUTOUPDATE: "1" } })
    let id = 0
    const pending = new Map<number, (v: any) => void>()
    const send = (msg: any) => proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n")
    const request = (method: string, params: any) => new Promise<any>((res) => { const i = ++id; pending.set(i, res); send({ id: i, method, params }) })
    
    let dirLocations = 0
    const seen = new Set<string>()
    ;(async () => {
      let buf = ""
      for await (const bytes of proc.stdout) {
        buf += new TextDecoder().decode(bytes)
        let nl
        while ((nl = buf.indexOf("\n")) >= 0) {
          const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1)
          if (!line) continue
          const msg = JSON.parse(line)
          if (msg.id !== undefined && pending.has(msg.id)) { pending.get(msg.id)!(msg); pending.delete(msg.id); continue }
          if (msg.method === "session/request_permission") { send({ id: msg.id, result: { outcome: { outcome: "selected", optionId: msg.params.options[0].optionId } } }); continue }
          if (msg.method && msg.id !== undefined) { send({ id: msg.id, error: { code: -32601, message: "not supported" } }); continue }
          const u = msg.params?.update
          if (u && (u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update")) {
            for (const loc of u.locations ?? []) {
              let isDir = false; try { isDir = statSync(loc.path).isDirectory() } catch {}
              if (isDir) dirLocations++
              const key = `${u.sessionUpdate} ${u.toolCallId} ${u.status ?? ""} ${loc.path}`
              if (!seen.has(key)) { seen.add(key); console.log(`${u.sessionUpdate} (${u.title ?? u.toolCallId}, ${u.status ?? "-"}) location ${loc.path}${isDir ? "  <-- DIRECTORY" : ""}`) }
            }
          }
        }
      }
    })()
    
    const init = await request("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } } })
    console.log("agent:", JSON.stringify(init.result?.agentInfo ?? init.error))
    const session = await request("session/new", { cwd: project, mcpServers: [] })
    if (session.error) throw new Error(JSON.stringify(session.error))
    const result = await Promise.race([
      request("session/prompt", { sessionId: session.result.sessionId, prompt: [{ type: "text", text: "list the files and grep the css" }] }),
      Bun.sleep(90_000).then(() => ({ timeout: true })),
    ])
    console.log("prompt result:", JSON.stringify(result.result ?? result.error ?? result))
    console.log(dirLocations ? `BUG: opencode sent ${dirLocations} directory location(s) to the ACP client` : "OK: no directory locations sent")
    proc.kill(); server.stop(true)
    process.exit(0)

    Run it: bun acp-e2e.ts

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions