Skip to content

acp: worktree rebind makes session permanently unloadable ("does not belong to cwd") #66573

Description

@flupkede

Summary

When opencode's worktree feature rebinds an existing session to a new worktree directory, an ACP client can never load that session again. session/load requires the session's (new) directory as cwd per the documented contract, but the client only knows the original workspace root — opencode never exposes the new directory to the client: not in the error message, not in session/list, and not via any session/update. The thread shows the same error on every panel reopen/restart, forever.

Environment

  • opencode version: 2.4.1 (stable, global bun install)
  • OS: Windows 11 (10.0.26200, win32 x64)
  • Terminal: ACP child process spawned by Zed (no TTY)
  • Shell: Git Bash (paths only)
  • Install/channel: stable
  • Active plugins: @slkiser/[email protected], local fast-compaction plugin — unrelated to the session-load path
  • ACP client: Zed, OpenCode agent via opencode acp

Reproduction

  1. In an ACP client (Zed), open a workspace at the project's main worktree <main> and start an OpenCode session. opencode binds the session to directory = <main> (confirmed: session_v2.directory).
  2. From within that session, have opencode create a new git worktree <wt> (worktree feature).
    • Result in ~/.local/share/opencode/opencode.db: the session row's directory is rewritten to <wt>, and <wt> is registered in the worktree table. Nothing is sent to the ACP client.
  3. Close and reopen the client (or just reopen the agent panel). Zed restores the thread and calls session/load with cwd = <main>.
  4. The load fails on every attempt:
Invalid params: session ses_dec8b3b56ffeHYhCTRAHy8Weo6 does not belong to cwd: <main>: {
  "sessionId": "ses_dec8b3b56ffeHYhCTRAHy8Weo6",
  "cwd": "<main>"
}

session/list with cwd = <main> also does not return the session (directory-scoped), so the thread is invisible and unresumable from the client. Reproducible 100%: this fires on every panel reopen (4 failed restore attempts logged within one morning via Zed's agent-panel error telemetry).

Expected Behavior

Per the documented ACP contract ("To load, resume, or fork a session, the client must pass that session's directory as cwd"), the client needs to know the session's directory. Either:

  1. opencode should not silently rebind an active ACP session's directory when creating a worktree, or
  2. it should tell the client — e.g. a session_info_update with _meta["opencode/directory"] (same pattern as the existing opencode/retry / opencode/compaction _meta keys), or
  3. minimally: expose the session's directory in session/list _meta and in the invalid-params error, so clients can recover (re-load with the right cwd or at least surface "session moved to ").

Actual Behavior

The client has no way to learn the session's new directory, session/load fails permanently with Invalid params ... does not belong to cwd, and the session is also hidden from session/list under the original cwd. The thread is dead from the client's perspective even though the session is intact and loadable from the worktree directory.

Additional Context

Timeline evidence from a real occurrence (opencode 2.4.1, opencode.db):

  • Session created 2026-11-25 17:05:53 (local) — before the worktree existed.
  • Worktree <wt> registered in the worktree table at 2026-11-25 18:21:58, strategy git.
  • session_v2.directory for that session now points to <wt>; the session was moved after creation.

Client side (Zed db, sidebar_threads): the thread row pins session_id to the workspace <main> with no notion of a directory change, so the client cannot comply with the contract even in principle.

Workaround confirmed: opening <wt> itself as the client workspace makes session/list (cwd = <wt>) return the session and it loads fine — which also confirms the diagnosis. The same pattern has already stranded several other sessions (session created before its worktree was registered).

Related but distinct: #60847 (worktree discovery cross-registers sibling dirs), #59371 (folder-scoped list hides sessions with duplicate project rows).

Redaction note: session title, local username and project paths are redacted; session id kept because it is required to follow the db timeline.

Activity

  1. added
    area/ide-acp
    type/bug
    version/v2
    on Nov 26, 2026
  2. opencodejr commented on Nov 26, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I reproduced this on 2.4.1 with a small ACP client script (attached below), and it still happens on the latest dev (314842df).

    What the script does:

    1. Runs session/new with cwd set to the main repo.
    2. Creates a git worktree and moves the session into it. I used the session.move API, which runs the same core move the agent's opencode.session.move tool uses.
    3. Restarts opencode acp, the way Zed restores a thread.

    After the restart:

    • session/list with cwd set to the main repo no longer returns the session.
    • session/load with that cwd fails every time with Invalid params: session ses_… does not belong to cwd: …/main.
    • session/load with the worktree as cwd works.

    While the session was moved, the ACP process sent nothing that carried the new directory; the only notification was an available_commands_update. I couldn't find any handling of session moves in the ACP code either. I've passed this to the maintainers.

    Reproduction script (repro.mjs)
    // Reproduces #66573: after a session is moved into a git worktree, ACP session/load with the
    // original cwd fails forever and nothing tells the ACP client about the new directory.
    // Usage: node repro.mjs            (uses `opencode` from PATH)
    //        OC_CMD="bun ... /path/index.ts" node repro.mjs
    import { spawn, execSync } from "node:child_process"
    import fs from "node:fs"
    import os from "node:os"
    import path from "node:path"
    
    const cmd = (process.env.OC_CMD ?? "opencode").split(" ")
    const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "oc-66573-")))
    const main = path.join(base, "main")
    const wt = path.join(base, "wt")
    fs.mkdirSync(main)
    const sh = (c, cwd = main) => execSync(c, { cwd, stdio: "pipe" }).toString()
    sh("git init -q && git config user.email a@b && git config user.name t && echo hi > a.txt && git add . && git commit -qm init")
    
    function acp() {
      const p = spawn(cmd[0], [...cmd.slice(1), "acp"], { cwd: main, stdio: ["pipe", "pipe", "inherit"] })
      let buf = "", id = 0
      const pending = new Map(), notes = []
      p.stdout.on("data", (d) => {
        buf += d
        let i
        while ((i = buf.indexOf("\n")) >= 0) {
          const line = buf.slice(0, i); buf = buf.slice(i + 1)
          if (!line.trim()) continue
          const msg = JSON.parse(line)
          if (msg.id !== undefined && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id) }
          else if (msg.method) {
            notes.push(msg)
            if (msg.id !== undefined) p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "n/a" } }) + "\n")
          }
        }
      })
      const req = (method, params) => new Promise((res) => {
        const myId = ++id; pending.set(myId, res)
        p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: myId, method, params }) + "\n")
      })
      return { p, req, notes }
    }
    
    const init = { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } } }
    let a = acp()
    await a.req("initialize", init)
    const created = await a.req("session/new", { cwd: main, mcpServers: [] })
    const sid = created.result?.sessionId
    console.log("session/new cwd=main ->", sid ?? JSON.stringify(created.error))
    
    // Create a git worktree and move the session into it, as the agent's
    // opencode.session.move tool does after worktree_create.
    sh(`git worktree add -q ${wt} -b feature`)
    const before = a.notes.length
    console.log(sh(`${cmd.join(" ")} api session.move --param sessionID=${sid} -d '${JSON.stringify({ directory: wt })}'`))
    await new Promise((r) => setTimeout(r, 3000))
    const after = a.notes.slice(before)
    console.log("ACP notifications after move:", JSON.stringify(after.map((n) => n.params?.update ?? n.method)))
    a.p.kill()
    
    // Client restarts and restores the thread with its workspace root, as Zed does.
    a = acp()
    await a.req("initialize", init)
    const listed = await a.req("session/list", { cwd: main })
    console.log("session/list cwd=main contains session:", !!listed.result?.sessions?.some((s) => s.sessionId === sid))
    for (let i = 1; i <= 2; i++) {
      const load = await a.req("session/load", { sessionId: sid, cwd: main, mcpServers: [] })
      console.log(`session/load cwd=main attempt ${i} ->`, JSON.stringify(load.error ?? "ok"))
    }
    const ok = await a.req("session/load", { sessionId: sid, cwd: wt, mcpServers: [] })
    console.log("session/load cwd=wt ->", JSON.stringify(ok.error ?? "ok"))
    a.p.kill()
    process.exit(0)

    Run it: bun repro.mjs

  3. LyleLiu666 commented on Nov 26, 2026

    @LyleLiu666

    I tested #66612 at 17c3eb1e06 with Zed 1.30.2 on macOS and the ACP SDK. Live rebinding worked: Zed received the new directory and a relative file read ran in the destination worktree.

    After a full Zed restart, both a session moved while connected and an already-moved session sent session/load with their original cwd and got -32602. The SDK loaded both sessions and replayed their history using the new cwd from data.directory.

    The patch below allows load and resume from a previous directory recorded for that session and still owned by its current project. With the same saved Zed profile and database, it reopened the original thread from the old cwd, replayed its history, and ran a follow-up file read in the new worktree. Windows remains unverified.

    Patch on my fork

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

    area/ide-acpplatform/windowsreproducedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions