Skip to content

send_message_to_thread omits the target turn ID, preventing exact completion correlation #40397

Open

Description

@dongkeren

What version of the Codex App are you using (From “About Codex” dialog)?

macOS desktop app host, installed bundle version 26.803.61601 (build 6396). Local Codex CLI: codex-cli 0.147.0-alpha.6.5.

What subscription do you have?

Not recorded for this reproduction; the completion-correlation contract should not depend on plan tier.

What platform is your computer?

macOS 26.5.2 (build 25F84), Apple Silicon / arm64.

What issue are you seeing?

The first-party task tools do not expose a stable way to correlate one successful
send_message_to_thread call with the target turn whose completion should later
be observed by wait_threads.

send_message_to_thread returns only threadId. wait_threads accepts only a
target threadId and an optional thread cursor. If two turns complete after the
saved cursor before the caller begins waiting, wait_threads reports the latest
turn, even when the caller needs the completion created by the first send.

This is a completion-correlation problem. It is not a claim that the later turn
failed, nor is it the delivery-acknowledgement failure reported in #29886.

What steps can reproduce the bug?

Use a harmless projectless target task B. Each prompt below only asks for an
exact text response and performs no tools or file changes.

  1. Let B become idle, then call:

    {
      "targets": [{"threadId": "<B>"}],
      "timeoutMs": 0
    }

    Save the returned polls[0].cursor as C0.

  2. From task A, call send_message_to_thread targeting B with:

    Reply exactly: X_DONE_20260824_C91E
    
  3. Observe the complete send result:

    {"threadId":"<B>"}

    No target turn ID or message/dispatch ID is returned.

  4. With read_thread, confirm X completed. In this run its turn ID ended in
    a952 and its final text was X_DONE_20260824_C91E.

  5. From task A, call send_message_to_thread again, targeting the same B, with:

    Reply exactly: Y_DONE_20260824_5B42
    
  6. With read_thread, confirm Y completed. In this run its different turn ID
    ended in db7a and its final text was Y_DONE_20260824_5B42.

  7. Only now call wait_threads with the cursor saved before X:

    {
      "targets": [{"threadId":"<B>", "afterCursor":"<C0>"}],
      "timeoutMs": 0
    }

Actual behavior

The late wait returns reason: "turnCompleted", Y's turn ID (…db7a), and the
Y response. Relevant fields from the returned result:

{
  "wake": {
    "reason": "turnCompleted",
    "turnId": "…db7a",
    "threadId": "<B>"
  },
  "polls": [
    {
      "latestAssistantMessage": {
        "turnId": "…db7a",
        "text": "Y_DONE_20260824_5B42"
      }
    }
  ]
}

The caller has no field with which to express “wait for the target turn created
by the X send.” Both sends have the same source and target thread IDs, so
thread-level provenance cannot disambiguate them. A read_thread immediately
after sending can sometimes infer the latest turn, but that is itself a
latest-state read and remains racy.

What is the expected behavior?

A successful send should expose a stable correlation handle, and the wait tool
should optionally wait for that exact unit without substituting a newer turn.

One minimal backward-compatible shape would be:

send_message_to_thread(...) -> { threadId, turnId }

wait_threads({
  targets: [{ threadId, turnId? }]
})

When turnId is provided, completion of a newer turn must not satisfy the wait.
When it is omitted, the existing thread-level/latest-turn behavior can remain
unchanged.

Additional information

How this issue was found

We found this issue by applying KFD's Work-level semantic invariants to the
task-management contracts in the Codex repository, then testing the predicted
gap against the live codex_app tool surface.

KFD is an open semantic model for durable agent Work. It keeps Work identity,
agent/thread execution, delegation receipts, provenance, and completion
authority distinct, rather than reconstructing them from session or thread
state.

One of those invariants is that a durable thread cannot serve as the identity
of an individual delegated unit of Work. Applying it here led us to check
whether send_message_to_thread returns the identity of the turn it creates,
and whether wait_threads can wait on that same identity. The black-box
reproduction above and the source analysis below confirm that the correlation
handle is missing.

The broader protocol analysis and six related boundary tests are discussed in
KFD #427.

Source analysis

Public commit 339751715c64496cb86246bfb3935f40e309dd3d shows the same
contract gap in the TUI-hosted task tools:

  • send_message_to_thread awaits start_turn(...) but discards the
    TurnStartResponse, then returns only threadId:
    "send_message_to_thread" => {
    let arguments: SendArguments = parse_arguments(params.arguments)?;
    if arguments.model.as_deref().is_some_and(str::is_empty) {
    return Err("model must not be empty".to_string());
    }
    validate_prompt(&arguments.prompt, MAX_INPUT_BYTES)?;
    let prompt = delegated_prompt(&params.thread_id, &arguments.prompt);
    validate_prompt(&prompt, MAX_DELEGATED_INPUT_BYTES)?;
    let thread = read_thread(&handle, &arguments.thread_id).await?;
    let exclude_turns = thread.history_mode == ThreadHistoryMode::Paginated;
    let _: ThreadResumeResponse = request_with_history_fallback(
    &handle,
    exclude_turns,
    |request_id, exclude_turns| ClientRequest::ThreadResume {
    request_id,
    params: ThreadResumeParams {
    thread_id: arguments.thread_id.clone(),
    exclude_turns,
    config: mcp_config.clone(),
    ..ThreadResumeParams::default()
    },
    },
    )
    .await?;
    register_background_thread(
    app_event_tx,
    &arguments.thread_id,
    /*task_tools_available*/ false,
    )
    .await?;
    start_turn(
    &handle,
    &arguments.thread_id,
    prompt,
    arguments.model,
    /*sandbox_policy*/ None,
    )
    .await?;
    Ok(json!({"threadId": arguments.thread_id}))
  • TurnStartResponse already contains the created turn:
    #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
    #[serde(rename_all = "camelCase")]
    #[ts(export_to = "v2/")]
    pub struct TurnStartResponse {
    pub turn: Turn,
    }
  • WaitTarget contains only threadId and afterCursor:
    struct WaitArguments {
    targets: Vec<WaitTarget>,
    timeout_ms: Option<u64>,
    }
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    struct WaitTarget {
    thread_id: String,
    after_cursor: Option<String>,
    }
  • wait_threads reads the latest turn and reports that turn on completion:
    "wait_threads" => {
    let arguments: WaitArguments = parse_arguments(params.arguments)?;
    let timeout_ms = arguments.timeout_ms.unwrap_or(MAX_WAIT_TIMEOUT_MS);
    if arguments.targets.is_empty() || arguments.targets.len() > MAX_WAIT_TARGETS {
    return Err(format!(
    "targets must contain between 1 and {MAX_WAIT_TARGETS} tasks"
    ));
    }
    if timeout_ms > MAX_WAIT_TIMEOUT_MS {
    return Err(format!("timeoutMs must not exceed {MAX_WAIT_TIMEOUT_MS}"));
    }
    let mut unique_targets = HashSet::new();
    for target in &arguments.targets {
    if same_thread_id(&target.thread_id, &params.thread_id) {
    return Err("wait_threads cannot wait on the calling task".to_string());
    }
    let canonical_id = ThreadId::from_string(&target.thread_id)
    .map(|thread_id| thread_id.to_string())
    .unwrap_or_else(|_| target.thread_id.clone());
    if !unique_targets.insert(canonical_id) {
    return Err("wait_threads received duplicate target tasks".to_string());
    }
    }
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let snapshot_deadline = if timeout_ms == 0 {
    Instant::now() + Duration::from_secs(/*secs*/ 5)
    } else {
    deadline
    };
    let result =
    |timed_out: bool, wake: Option<Value>, polls: Vec<Value>, errors: Vec<Value>| {
    let mut result = json!({"timedOut": timed_out, "wake": wake, "polls": polls});
    if !errors.is_empty() {
    result["errors"] = json!(errors);
    }
    result
    };
    loop {
    let mut polls = Vec::with_capacity(arguments.targets.len());
    let mut errors = Vec::new();
    let mut wake = None;
    for (index, target) in arguments.targets.iter().enumerate() {
    let now = Instant::now();
    let target_deadline = now
    + snapshot_deadline.saturating_duration_since(now)
    / (arguments.targets.len() - index) as u32;
    match tokio::time::timeout_at(
    target_deadline,
    read_thread(&handle, &target.thread_id),
    )
    .await
    {
    Ok(Ok(thread)) => {
    let turns_page = tokio::time::timeout_at(
    target_deadline,
    handle.request_typed::<ThreadTurnsListResponse>(
    ClientRequest::ThreadTurnsList {
    request_id: RequestId::String(format!(
    "tui-dynamic-{}",
    Uuid::new_v4()
    )),
    params: ThreadTurnsListParams {
    thread_id: thread.id.clone(),
    cursor: None,
    limit: Some(1),
    sort_direction: Some(SortDirection::Desc),
    items_view: Some(TurnItemsView::Summary),
    },
    },
    ),
    )
    .await;
    let latest_turn = match turns_page {
    Ok(Ok(page)) => page.data.into_iter().next(),
    Ok(Err(TypedRequestError::Server { source, .. }))
    if crate::app_server_session::is_history_pagination_unsupported(
    &source,
    ) =>
    {
    tokio::time::timeout_at(
    target_deadline,
    request::<ThreadReadResponse>(&handle, |request_id| {
    ClientRequest::ThreadRead {
    request_id,
    params: ThreadReadParams {
    thread_id: thread.id.clone(),
    include_turns: true,
    },
    }
    }),
    )
    .await
    .ok()
    .and_then(Result::ok)
    .and_then(|response| response.thread.turns.into_iter().next_back())
    }
    _ => None,
    };
    let latest_items = if let Some(turn) = &latest_turn {
    tokio::time::timeout_at(
    target_deadline,
    request::<ThreadItemsListResponse>(&handle, |request_id| {
    ClientRequest::ThreadItemsList {
    request_id,
    params: ThreadItemsListParams {
    thread_id: thread.id.clone(),
    turn_id: Some(turn.id.clone()),
    cursor: None,
    limit: Some(20),
    sort_direction: Some(SortDirection::Desc),
    },
    }
    }),
    )
    .await
    .ok()
    .and_then(Result::ok)
    .map(|page| page.data)
    .or_else(|| {
    Some(
    turn.items
    .iter()
    .rev()
    .take(20)
    .cloned()
    .map(|item| ThreadItemEntry {
    turn_id: turn.id.clone(),
    item,
    })
    .collect(),
    )
    })
    } else {
    None
    };
    let cursor = serde_json::to_string(&json!({
    "updatedAt": thread.updated_at,
    "status": thread.status,
    "turnId": latest_turn.as_ref().map(|turn| &turn.id),
    "turnStatus": latest_turn.as_ref().map(|turn| &turn.status),
    "latestItemId": latest_items
    .as_ref()
    .and_then(|items| items.first())
    .map(|entry| entry.item.id())
    }))
    .map_err(|error| error.to_string())?;
    let changed = target.after_cursor.as_deref() != Some(cursor.as_str());
    if wake.is_none() {
    wake = match (&thread.status, &latest_turn) {
    (ThreadStatus::Idle, Some(turn))
    if changed
    && turn.status
    != codex_app_server_protocol::TurnStatus::InProgress =>
    {
    Some(json!({
    "threadId": thread.id,
    "reason": "turnCompleted",
    "turnId": turn.id
    }))

The black-box observation above is from the codex_app tool surface. I have not
verified that the desktop handler and the public TUI host share the identical
implementation; the source links show that the same externally visible contract
shape also exists in that public commit.

Related issues

Activity

  1. added
    app
    on Aug 24, 2026
  2. added
    bug
    subagent
    on Aug 24, 2026
  3. eddiez529 commented on Aug 30, 2026

    @eddiez529

    I pushed a bounded proof-of-fix to my public fork (no upstream PR yet):

    https://github.com/junwei529/codex/commit/55c1e100f5cfa7c84776f1061309fc085f165114

    The change captures the existing TurnStartResponse returned by start_turn and makes send_message_to_thread return:

    {"threadId":"<target thread>","turnId":"<accepted turn>"}

    It also updates the callable tool description and extends the existing background-turn integration test with a non-empty turnId assertion.

    Verification completed:

    • git diff --check / staged-diff checks passed.
    • Native Codex review (gpt-5.6-terra, high) completed with no findings.
    • I could not run the repository's just fmt or just test -p codex-tui commands on this host because neither the Rust toolchain nor just is installed; I did not install dependencies for this investigation.

    Scope note: this only exposes the accepted turn identity to the caller. It does not yet add turnId-aware waiting/correlation to wait_threads, so that remaining half of exact completion tracking is still open.

  4. rtol5 commented on Sep 30, 2026

    @rtol5

    This also matters when a release coordinator contacts existing persistent branch owners. A chat can finish unrelated work, receive another prompt, or already have an active turn when the coordinator sends its request. The next observed completion does not establish that the requested branch checks finished.

    Our workaround uses a caller request ID and exact target identity. Active steering returns the same accepted turn ID, and bounded request-specific input/result reads establish what arrived and what was answered. Queue acceptance remains a separate state; an arbitrary later completion cannot be treated as the corresponding response.

    A native receipt containing request/message ID plus target turn ID when assigned, with status/wait operations that can follow that request, would be useful. For queued delivery, the turn may not exist at acceptance time, so retaining the request-to-turn mapping is important.

    We have not independently reproduced this issue's two-completion race with the native sender, which is absent in our current sessions. This is additional workflow evidence and a tested adapter design, not a claim that the native bug is fixed.

  5. rtol5 commented on Sep 30, 2026

    @rtol5

    Update to my earlier adapter-only observation: we now completed a genuine Desktop-native send/return between original persistent owners on a Linux VM, using Desktop 26.928.21956 with existing app-server 0.159.1.

    Native source-thread provenance is useful, but our release coordinator still correlates the requested work through a request ID in the payload and an explicit substantive reply. A source/target thread pair or the next completed turn alone is insufficient when an owner has other work.

    A stable dispatch/request handle, mapped to the target turn when assigned and accepted by read/wait/status, remains valuable even when native delivery works. We have not repeated this issue's two-completion race with the sidecar, so this is additional workflow evidence rather than a bug-fix claim.

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

    appbugsubagent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions