Skip to content

cli: opencode run hangs if a child session is busy when the root finishes #62636

Open

Description

@ivopogace

Description

opencode run never exits if a child session created with parentID is still busy when the root's turn ends.

Plugins

none

OpenCode version

2.2.6

Steps to reproduce

  1. Create a root session and a child with parentID set to the root, and give the child a long prompt.
  2. While the child is still busy, run opencode run --server --session "hi".
  3. The root replies, the child finishes, and the run never exits. Without parentID it exits.

Tested script (local mock model, no API key):

repro.sh
#!/usr/bin/env bash
# `opencode run` never exits when a non-job child session (created with parentID)
# is still busy when the root's turn ends. Needs opencode, node, curl and jq.
set -u
W=$(mktemp -d)
mkdir -p "$W/project"
cd "$W"

# A mock OpenAI-compatible model: replies at once, or after 10 s when the prompt says SLOW.
cat >mock.mjs <<'EOF'
import { createServer } from "node:http"
const text = (c) => typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => p.text ?? "").join("") : ""
const chunk = (delta, finish) => `data: ${JSON.stringify({ id: "x", object: "chat.completion.chunk", created: 0, model: "chat",
  choices: [{ index: 0, delta, finish_reason: finish }], ...(finish ? { usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } } : {}) })}\n\n`
createServer((req, res) => {
  let raw = ""
  req.on("data", (d) => (raw += d))
  req.on("end", async () => {
    const body = raw ? JSON.parse(raw) : {}
    const last = text((body.messages ?? []).findLast((m) => m.role === "user")?.content)
    const slow = body.tools?.length && last.includes("SLOW")
    if (slow) await new Promise((r) => setTimeout(r, 10_000))
    const reply = !body.tools?.length ? "title" : slow ? "CHILD DONE" : "ROOT DONE"
    console.log(new Date().toISOString(), req.headers["x-opencode-session-id"], reply)
    if (!body.stream) {
      res.writeHead(200, { "content-type": "application/json" })
      return res.end(JSON.stringify({ id: "x", object: "chat.completion", created: 0, model: "chat",
        choices: [{ index: 0, message: { role: "assistant", content: reply }, finish_reason: "stop" }],
        usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }))
    }
    res.writeHead(200, { "content-type": "text/event-stream" })
    res.write(chunk({ role: "assistant", content: reply }, null))
    res.write(chunk({}, "stop"))
    res.end("data: [DONE]\n\n")
  })
}).listen(4599, "127.0.0.1")
EOF

cat >project/opencode.json <<'EOF'
{
  "providers": {
    "mock": {
      "package": "aisdk:@ai-sdk/openai-compatible",
      "settings": { "baseURL": "http://127.0.0.1:4599/v1", "apiKey": "mock" },
      "models": { "chat": {} }
    }
  },
  "model": "mock/chat",
  "update": "disable",
  "permissions": [{ "action": "*", "resource": "*", "effect": "allow" }]
}
EOF

# A throwaway home, so no user config or plugins take part.
export HOME=$W/home XDG_CONFIG_HOME=$W/home/.config XDG_DATA_HOME=$W/home/.local/share XDG_STATE_HOME=$W/home/.local/state XDG_CACHE_HOME=$W/home/.cache
mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_STATE_HOME" "$XDG_CACHE_HOME"
export OPENCODE_PASSWORD=repro
SERVER=http://127.0.0.1:4600
node mock.mjs >mock.log 2>&1 &
MOCK=$!
(cd project && exec opencode serve --hostname 127.0.0.1 --port 4600 >../server.log 2>&1 </dev/null) &
SRV=$!
trap 'kill $MOCK $SRV 2>/dev/null' EXIT
for _ in $(seq 60); do curl -sf -u "opencode:$OPENCODE_PASSWORD" "$SERVER/api/info" >/dev/null && break; sleep 0.5; done
echo "$(opencode --version)"

api_post() { curl -sf -u "opencode:$OPENCODE_PASSWORD" -X POST -H 'content-type: application/json' --data "$2" "$SERVER/api/$1"; }

# $1 name, $2 "parent" or "orphan", $3 seconds between starting the child's turn and the run
attempt() {
  root=$(api_post session "{\"location\":{\"directory\":\"$W/project\"}}" | jq -r '.data.id')
  if [ "$2" = parent ]; then
    child=$(api_post session "{\"parentID\":\"$root\"}" | jq -r '.data.id')
  else
    child=$(api_post session "{\"location\":{\"directory\":\"$W/project\"}}" | jq -r '.data.id')
  fi
  api_post "session/$child/prompt" '{"text":"SLOW child work"}' >/dev/null &
  prompter=$!
  sleep "$3"
  start=$(date +%s)
  (cd project && timeout 45 opencode run --server "$SERVER" --session "$root" --format json "hi" </dev/null >"$W/$1.out" 2>&1)
  code=$?
  echo "$1: opencode run exit=$code after $(($(date +%s) - start))s (124 = killed by the 45 s timeout); root replied: $(grep -c 'ROOT DONE' "$W/$1.out")"
  wait "$prompter"
}

attempt child-busy parent 1       # child still busy when the root ends: hangs
attempt no-parent orphan 1        # same child without parentID: exits
attempt child-done-first parent 12 # child finished before the run: exits
echo "--- model requests"; cat mock.log

Screenshot

No response

Operating System

Debian 13 (Docker container)

Terminal

n/a

Activity

  1. opencodejr commented on Nov 7, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report and the script, they made this easy to confirm. I can reproduce it on 2.2.6, and it still happens on the latest dev (c33eaa1).

    I ran your script with a mock model:

    • Child created with parentID, still busy when the root's turn ends: the root replies at once and the child finishes after about 10 s, but opencode run never exits and is killed by the 45 s timeout (exit 124).
    • Same child without parentID: the run exits 0 right away.
    • parentID child that finished before the run started: the run exits 0 right away.

    The script below is your script with one change: it can also run OpenCode from a source checkout.

    A likely cause, not yet confirmed with a fix: in packages/cli/src/run/noninteractive.ts, the run treats the busy child as part of its own work because of its parentID, so it keeps waiting. But it only wakes up again when a subagent job's session finishes. A child created through the API isn't a job, so its completion never wakes the wait.

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # #62636: `opencode run` never exits when a non-job child session (created with parentID)
    # is still busy when the root's turn ends. Needs opencode, node, curl and jq.
    # Based on the author's script. Set OC (e.g. OC="bun ... packages/cli/src/index.ts") to run from source.
    set -u
    OC=${OC:-opencode}
    W=$(mktemp -d)
    mkdir -p "$W/project"
    cd "$W"
    
    # Mock OpenAI-compatible model: replies at once, or after 10 s when the prompt says SLOW.
    cat >mock.mjs <<'EOF'
    import { createServer } from "node:http"
    const text = (c) => typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => p.text ?? "").join("") : ""
    const chunk = (delta, finish) => `data: ${JSON.stringify({ id: "x", object: "chat.completion.chunk", created: 0, model: "chat",
      choices: [{ index: 0, delta, finish_reason: finish }], ...(finish ? { usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } } : {}) })}\n\n`
    createServer((req, res) => {
      let raw = ""
      req.on("data", (d) => (raw += d))
      req.on("end", async () => {
        const body = raw ? JSON.parse(raw) : {}
        const last = text((body.messages ?? []).findLast((m) => m.role === "user")?.content)
        const slow = body.tools?.length && last.includes("SLOW")
        if (slow) await new Promise((r) => setTimeout(r, 10_000))
        const reply = !body.tools?.length ? "title" : slow ? "CHILD DONE" : "ROOT DONE"
        console.log(new Date().toISOString(), req.headers["x-opencode-session-id"], reply)
        if (!body.stream) {
          res.writeHead(200, { "content-type": "application/json" })
          return res.end(JSON.stringify({ id: "x", object: "chat.completion", created: 0, model: "chat",
            choices: [{ index: 0, message: { role: "assistant", content: reply }, finish_reason: "stop" }],
            usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }))
        }
        res.writeHead(200, { "content-type": "text/event-stream" })
        res.write(chunk({ role: "assistant", content: reply }, null))
        res.write(chunk({}, "stop"))
        res.end("data: [DONE]\n\n")
      })
    }).listen(4599, "127.0.0.1")
    EOF
    
    cat >project/opencode.json <<'EOF'
    {
      "providers": {
        "mock": {
          "package": "aisdk:@ai-sdk/openai-compatible",
          "settings": { "baseURL": "http://127.0.0.1:4599/v1", "apiKey": "mock" },
          "models": { "chat": {} }
        }
      },
      "model": "mock/chat",
      "update": "disable",
      "permissions": [{ "action": "*", "resource": "*", "effect": "allow" }]
    }
    EOF
    
    export HOME=$W/home XDG_CONFIG_HOME=$W/home/.config XDG_DATA_HOME=$W/home/.local/share XDG_STATE_HOME=$W/home/.local/state XDG_CACHE_HOME=$W/home/.cache
    mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_STATE_HOME" "$XDG_CACHE_HOME"
    export OPENCODE_PASSWORD=repro
    SERVER=http://127.0.0.1:4600
    node mock.mjs >mock.log 2>&1 &
    MOCK=$!
    (cd project && exec $OC serve --hostname 127.0.0.1 --port 4600 >../server.log 2>&1 </dev/null) &
    SRV=$!
    trap 'kill $MOCK $SRV 2>/dev/null; pkill -P $SRV 2>/dev/null' EXIT
    for _ in $(seq 120); do curl -sf -u "opencode:$OPENCODE_PASSWORD" "$SERVER/api/info" >/dev/null && break; sleep 0.5; done
    echo "version: $(cd project && $OC --version)"
    
    api_post() { curl -sf -u "opencode:$OPENCODE_PASSWORD" -X POST -H 'content-type: application/json' --data "$2" "$SERVER/api/$1"; }
    
    attempt() {
      root=$(api_post session "{\"location\":{\"directory\":\"$W/project\"}}" | jq -r '.data.id')
      if [ "$2" = parent ]; then
        child=$(api_post session "{\"parentID\":\"$root\"}" | jq -r '.data.id')
      else
        child=$(api_post session "{\"location\":{\"directory\":\"$W/project\"}}" | jq -r '.data.id')
      fi
      api_post "session/$child/prompt" '{"text":"SLOW child work"}' >/dev/null &
      prompter=$!
      sleep "$3"
      start=$(date +%s)
      (cd project && timeout 45 $OC run --server "$SERVER" --session "$root" --format json "hi" </dev/null >"$W/$1.out" 2>&1)
      code=$?
      echo "$1: opencode run exit=$code after $(($(date +%s) - start))s (124 = killed by the 45 s timeout); root replied: $(grep -c 'ROOT DONE' "$W/$1.out")"
      wait "$prompter"
    }
    
    attempt child-busy parent 1        # child still busy when the root ends: hangs
    attempt no-parent orphan 1         # same child without parentID: exits
    attempt child-done-first parent 12 # child finished before the run: exits
    echo "--- model requests"; cat mock.log

    Run it: bash repro.sh

  2. iceteaSA commented on Nov 10, 2026

    @iceteaSA

    A second trigger reaches the same hang through a different branch of background(): a pending inbox row in the run's own session. I reproduced it on 2.2.6 with no plugins; background() is unchanged on current dev.

    Code path (packages/cli/src/run/noninteractive.ts at v2.2.6)

    • The settle loop exits only through if (!pending) return (:248).
    • background() returns running, which is an empty array, on two branches. An empty array is truthy, so the loop does not return:
      • :199-202: if (inboxes.some((inbox) => inbox.length > 0)) return running. A pending inbox row in a session of state.jobSessions.
      • :203-206: if (await ownsSession(sessionID)) return running. An active session that ownsSession claims. This is the busy parentID child of this issue.
    • The loop then waits on state.ended (:253). Only a terminal event of a session in state.jobSessions resolves it (:164-170).
      • An input admitted with resume: false never gets a wake, so no terminal event comes.
      • A child that was not started as a job is not in state.jobSessions, so its own terminal event does not resolve the wait either.

    Steps to reproduce trigger A

    1. Start a server. Subscribe to its event stream.
    2. Run opencode run --format json --session <id> "reply ok".
    3. When session.execution.succeeded arrives for that session, admit an input that does not wake the session:
      POST /api/session/<id>/synthetic with {"id": "...", "text": "...", "description": "...", "delivery": "steer", "resume": false}.
    4. The reply prints, and the session is idle with an idle message after the prompt. opencode run does not exit. It printed nothing more until a timeout stopped it (exit 124) after 70–100 s.
    5. A second opencode run on the same session promotes the pending row with its prompt and exits normally in about 2 s.

    Results: 3 of 4 attempts hung. In the 4th attempt the input arrived before the last boundary and was promoted with the prompt. During each hang, GET /api/session/active was empty and the session inbox held exactly one row on every sample. The same probe without the synthetic input exited normally on 6 of 6 runs, both first and second run after a server start.

    This is easy to hit with plugins. Any plugin that admits a notice with resume: false after the turn's last boundary leaves opencode run running with no limit. After SIGTERM, stderr shows Still pending: nothing tracked; the stuck finalizer is outside any LayerNode layer, because the run handler's finalizer waits on the same promise.

    A possible fix is to make background() wait only for work that can still produce a terminal event that the loop observes:

    • ignore inbox rows that will not get a wake;
    • add sessions claimed by ownsSession to state.jobSessions, so that their terminal events resolve state.ended.
  3. ivopogace commented on Nov 10, 2026

    @ivopogace
    Author

    Thanks @iceteaSA, you're right. I tested both cases:

    Maintainers: should I open a separate issue for the second case, or handle both in #62643?

  4. metamountain commented on Nov 27, 2026

    @metamountain

    Another data point on 2.3.0 (Windows 11, npm global install), and in our setup it happens without any child sessions: task/agent/subagent are denied in the config, so no session with parentID is ever created.

    Invocation: opencode run --standalone --archived --format json --thinking -m <openai-compatible local model> "<prompt>"

    Symptom: the final step_finish event with reason: "stop" arrives, no further model requests are made, and the process never exits. We work around it with a watchdog that kills the process tree 60 s after the final stop step. It happens on some runs, not all; we did not see it before 2.3.0.

    So the settle loop seems to wait on something other than a busy child here; possibly the second (pending inbox / synthetic) trigger mentioned above. Happy to run a debug build or collect logs if that helps.

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