GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ACP: parent's auto-resumed turn after background shell completion emits zero session/update · Issue #64119 · anomalyco/opencode

ACP: parent's auto-resumed turn after background shell completion emits zero session/update #64119

New issue
Copy link
New issue
Copy link
Closed
#64262
Closed
ACP: parent's auto-resumed turn after background shell completion emits zero session/update#64119
#64262
Copy link
Labels
area/ide-acpEditor integrations and ACPplatform/macosmacOSstatus/repro-simulatedReproduced with a simulated model or mocktype/bugSomething is brokenversion/v2OpenCode 2.x

Description

@raffaelefarinaro
raffaelefarinaro
opened on Nov 15, 2026
Issue body actions

Description

When a parent session starts a background shell (shell tool, background: true) and the shell finishes after session/prompt has already returned end_turn, core wakes the parent correctly: the <shell … state="completed"> message lands in the parent session and a full assistant turn runs and is persisted. But the ACP client receives zero session/update notifications for that resumed turn, so it never sees the agent's reaction.

This is the shell counterpart of #55760, which fixed the same problem for background subagents (#55834, #63395). Subagent wake-ups now stream correctly over ACP; background shells do not.

Likely cause. In packages/cli/src/acp/turn.ts, handoff keeps following the session after the turn only while subagent children are open:

opencode/packages/cli/src/acp/turn.ts

Lines 323 to 348 in aa2960f

const handoff = Effect.fnUntraced(function* (
attached: Attached,
turn: Turn,
exit: Exit.Exit<ACPTranslate.Terminal, ACPError.Failure>,
) {
const close = Scope.close(turn.subscription.scope, Exit.void)
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* close
const state = yield* Ref.get(turn.state)
if (state.openChildren.size === 0) {
if (state.children.size > 0) backgrounds.set(attached, { state: turn.state })
return yield* close
}
const responded = yield* ACPConnection.Responded
const nextState = yield* Ref.make({ ...state, started: false })
const cancelled = yield* Deferred.make<void>()
// Children outlive a cancelled turn, so their asks and report-triggered turns still reach the client.
const background = Effect.withFiber((fiber) => {
backgrounds.set(attached, { state: nextState, fiber })
return Effect.exit(responded).pipe(
Effect.andThen(
followChildren({ ...turn, ctx: { ...turn.ctx, start: undefined }, state: nextState, cancelled }),
),
Effect.interruptible,
)
}).pipe(Effect.ignore, Effect.ensuring(close), Effect.withSpan("cli.acp.turn.background"))
yield* input.sessions.fork(attached, background).pipe(Effect.catchTag("ACPSessionNotFoundError", () => close))

With no open children it closes the subscription (L331–335), so the turn started by the shell's completion has no listener. Running background shells are not considered.

Expected. The resumed parent turn streams as ordinary session/update notifications, the same as for a completed background subagent. That is: keep following while the session has running background shells, as handoff already does for openChildren.

Plugins

Not checked. The repro uses only the built-in shell tool.

OpenCode version

2.3.0 (opencode acp, agentInfo.version: "2.3.0")

Steps to reproduce

  1. Start opencode acp and send initialize, then session/new.
  2. session/prompt with:
    Use the shell tool with background: true to run `sleep 15 && echo BG_REPRO_DONE`.
    Do not wait for it. Reply with exactly STARTED and end your turn.
    When the shell completes, reply with exactly RESUMED.
    
  3. Keep reading stdout for 75 s after the prompt returns.

What the ACP client receives:

  4.1s tool_call_update  shell  in_progress  {"command":"sleep 15 && echo BG_REPRO_DONE","background":true}
  4.3s tool_call_update  shell  completed
  7.4s agent_message_chunk "STARTED"
  7.4s session/prompt → {"stopReason":"end_turn"}
 82.7s (nothing else received)

What the session contains (read back through opencode serve, GET /api/session/{id}/message):

assistant   "STARTED"
idle        outcome: succeeded
user (synthetic)  <shell id="sh_…" state="completed" command="sleep 15 && echo BG_REPRO_DONE"> BG_REPRO_DONE </shell>   (+12 s)
assistant   "RESUMED"                                                                                               (+15 s)
idle        outcome: succeeded

So the wake-up and the RESUMED turn happen server-side about 15 s after the prompt returned, but none of it reaches the ACP client.

Screenshot

N/A

Operating System

macOS 27.0.1

Terminal

N/A (stdio ACP client)

Activity

  1. opencodejr
    added
    area/ide-acpEditor integrations and ACP
    platform/macosmacOS
    type/bugSomething is broken
    version/v2OpenCode 2.x
    on Nov 15, 2026
  2. opencodejr commented on Nov 15, 2026

    @opencodejr
    opencodejrBot
    on Nov 15, 2026
    Contributor
    More actions

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    Thanks for the detailed report. I reproduced this on 2.3.0 using a local mock model server in place of a real provider.

    What I did:

    1. Ran opencode acp and sent initialize, session/new and session/prompt.
    2. The mocked model started sleep 15 && echo BG_REPRO_DONE with the shell tool and background: true, then replied STARTED.
    3. session/prompt returned end_turn.

    About 15 s later the server sent the model the <shell … state="completed">BG_REPRO_DONE</shell> wake-up and the RESUMED turn ran. The ACP client got 0 session/update notifications in the 45 s after end_turn.

    It still happens on the latest dev (aa2960fa2). The script below reproduces it, with opencode from PATH or a checkout via OC_DEV.

    Related: #55760 (the same symptom for background subagents, fixed by #63395).

    Reproduction script (repro.ts)
    // Reproduction for anomalyco/opencode#64119: ACP drops the parent's turn resumed by a background shell.
    // Runs a mock OpenAI-compatible model server and drives `opencode acp` over stdio.
    // Usage: bun /workspace/repro/repro.ts            (uses `opencode` from PATH)
    //        OC_DEV=/workspace/repo bun /workspace/repro/repro.ts   (runs the checkout)
    import { mkdtempSync, writeFileSync } from "node:fs"
    import { tmpdir } from "node:os"
    import { join } from "node:path"
    
    let calls = 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 base = { id: "x", object: "chat.completion.chunk", created: 0, model: "mock" }
    const text = (t: string) => sse([
      { ...base, choices: [{ index: 0, delta: { role: "assistant", content: t } }] },
      { ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 } },
    ])
    const server = Bun.serve({
      port: 0,
      async fetch(req) {
        const body: any = await req.json().catch(() => ({}))
        const all = JSON.stringify(body.messages ?? [])
        calls++
        console.error(`[mock] request #${calls}, ${body.messages?.length} messages, last role=${body.messages?.at(-1)?.role}: ${JSON.stringify(body.messages?.at(-1)?.content).slice(0, 160)}`)
        if (all.includes("BG_REPRO_DONE\\n") || /state=\\?"completed/.test(all) && all.includes("<shell")) return text("RESUMED")
        if (body.messages?.at(-1)?.role === "tool") return text("STARTED")
        return sse([
          { ...base, choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "shell", arguments: "" } }] } }] },
          { ...base, choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: JSON.stringify({ command: "sleep 15 && echo BG_REPRO_DONE", description: "bg", background: true }) } }] } }] },
          { ...base, choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }], usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 } },
        ])
      },
    })
    
    const dir = mkdtempSync(join(tmpdir(), "acp-repro-"))
    const home = mkdtempSync(join(tmpdir(), "acp-home-"))
    writeFileSync(join(dir, "opencode.jsonc"), JSON.stringify({
      model: "mock/mock",
      permissions: { "*": "allow" },
      providers: { mock: { name: "Mock", env: ["MOCK_API_KEY"], package: "@opencode/ai/providers/openai-compatible",
        settings: { baseURL: `http://127.0.0.1:${server.port}/v1` }, models: { mock: { name: "Mock" } } } },
    }))
    const cmd = process.env.OC_DEV
      ? ["bun", "--conditions=browser", `--preload=${process.env.OC_DEV}/packages/tui/node_modules/@opentui/solid/scripts/preload.js`, `${process.env.OC_DEV}/packages/cli/src/index.ts`, "acp"]
      : ["opencode", "acp"]
    const proc = Bun.spawn(cmd, { cwd: dir, stdin: "pipe", stdout: "pipe", stderr: "inherit",
      env: { ...process.env, ...(process.env.OC_DEV ? { BUN_OPTIONS: `--conditions=browser --preload=${process.env.OC_DEV}/packages/tui/node_modules/@opentui/solid/scripts/preload.js` } : {}), MOCK_API_KEY: "x", XDG_DATA_HOME: join(home, "data"), XDG_CONFIG_HOME: join(home, "config"), XDG_STATE_HOME: join(home, "state"), XDG_CACHE_HOME: join(home, "cache") } })
    const t0 = Date.now()
    const ts = () => ((Date.now() - t0) / 1000).toFixed(1).padStart(5) + "s"
    let id = 0
    const pending = new Map<number, (v: any) => void>()
    const send = (method: string, params: any) => new Promise<any>((res) => {
      const i = ++id; pending.set(i, res)
      proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: i, method, params }) + "\n"); proc.stdin.flush()
    })
    let promptReturned = 0, afterUpdates = 0
    ;(async () => {
      let buf = ""
      for await (const chunk of proc.stdout) {
        buf += new TextDecoder().decode(chunk)
        let n
        while ((n = buf.indexOf("\n")) >= 0) {
          const line = buf.slice(0, n); buf = buf.slice(n + 1)
          if (!line.trim()) continue
          const msg = JSON.parse(line)
          if (msg.id && pending.has(msg.id)) { pending.get(msg.id)!(msg); pending.delete(msg.id); continue }
          if (msg.method === "session/update") {
            const u = msg.params.update
            if (promptReturned) afterUpdates++
            console.log(`${ts()} ${promptReturned ? "[AFTER end_turn] " : ""}${u.sessionUpdate} ${u.status ?? ""} ${u.content?.text ? JSON.stringify(u.content.text) : ""}`)
          } else if (msg.method) {
            console.log(`${ts()} request from agent: ${msg.method}`)
            if (msg.id) proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { outcome: { outcome: "selected", optionId: "allow" } } }) + "\n")
          }
        }
      }
    })()
    console.log(await send("initialize", { protocolVersion: 1, clientCapabilities: {} }).then((r) => `initialize -> ${r.result?.agentInfo?.version ?? JSON.stringify(r.error)}`))
    const s = await send("session/new", { cwd: dir, mcpServers: [] })
    if (!s.result) { console.log("session/new failed", JSON.stringify(s)); process.exit(1) }
    const sessionId = s.result.sessionId
    const r = await send("session/prompt", { sessionId, prompt: [{ type: "text", text: "Run the background shell, reply STARTED, then RESUMED when it completes." }] })
    promptReturned = Date.now()
    console.log(`${ts()} session/prompt -> ${JSON.stringify(r.result ?? r.error)}`)
    await Bun.sleep(45_000)
    console.log(`${ts()} mock model requests: ${calls} (the last one carries the <shell state="completed"> wake-up; mock answers it with RESUMED)`)
    console.log(`${ts()} session/update notifications after end_turn: ${afterUpdates}`)
    proc.kill(); server.stop(true); process.exit(0)

    Run it: bun repro.ts

  3. opencodejr
    added
    status/repro-simulatedReproduced with a simulated model or mock
    on Nov 15, 2026
  4. r266-tech commented on Nov 16, 2026

    @r266-tech
    r266-tech
    on Nov 16, 2026
    Contributor
    More actions

    Candidate: r266-tech@2754a41

    I reproduced this with a real opencode acp subprocess and a background shell released by a file signal after end_turn. The patch retains the existing subscription for background shell work, checking job → inbox → active in the same order as the noninteractive client. It preserves following across another prompt and retires the subscription when work clears. Ordinary prompts make no background queries.

    Full CLI: 405 pass / 9 skip / 0 fail; unmodified dev fails the five new background cases, including the subprocess reproduction. Concurrent randomized repeats: 120 pass. Root bun run check (35 tasks) and CLI typecheck:tsc pass.

    Local macOS/Bun 1.4.4 with a scripted SSE provider; no real provider tested. The repository’s three-open-PR limit prevents submission, so the branch is available for review/reuse.

  5. neriousy
    closed this as completedin #64262on Nov 16, 2026
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-acpEditor integrations and ACPplatform/macosmacOSstatus/repro-simulatedReproduced with a simulated model or mocktype/bugSomething is brokenversion/v2OpenCode 2.x

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.