Repository navigation
Description
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.
-
Let B become idle, then call:
{ "targets": [{"threadId": "<B>"}], "timeoutMs": 0 }Save the returned
polls[0].cursorasC0. -
From task A, call
send_message_to_threadtargeting B with:Reply exactly: X_DONE_20260824_C91E -
Observe the complete send result:
{"threadId":"<B>"}No target turn ID or message/dispatch ID is returned.
-
With
read_thread, confirm X completed. In this run its turn ID ended in
a952and its final text wasX_DONE_20260824_C91E. -
From task A, call
send_message_to_threadagain, targeting the same B, with:Reply exactly: Y_DONE_20260824_5B42 -
With
read_thread, confirm Y completed. In this run its different turn ID
ended indb7aand its final text wasY_DONE_20260824_5B42. -
Only now call
wait_threadswith 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_threadawaitsstart_turn(...)but discards the
TurnStartResponse, then returns onlythreadId:
codex/codex-rs/tui/src/dynamic_tools.rs
Lines 739 to 777 in 3397517
"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(¶ms.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})) TurnStartResponsealready contains the createdturn:
codex/codex-rs/app-server-protocol/src/protocol/v2/turn.rs
Lines 163 to 168 in 3397517
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct TurnStartResponse { pub turn: Turn, } WaitTargetcontains onlythreadIdandafterCursor:
codex/codex-rs/tui/src/dynamic_tools.rs
Lines 132 to 142 in 3397517
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_threadsreads the latest turn and reports that turn on completion:
codex/codex-rs/tui/src/dynamic_tools.rs
Lines 826 to 984 in 3397517
"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, ¶ms.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
- send_message_to_thread reports handler error even when delegation is delivered #29886 requests reliable delivery acknowledgement when a send succeeds but a
handler reports failure. This report assumes successful sends and concerns
correlation with the later completion. - RFC: Persistent work threads with bounded command dispatch #35846 proposes a broader persistent work-thread / command-ID abstraction.
This report does not require that abstraction; the minimal request is an exact
target-turn handle for the already shipped send/wait tools.
Activity
eddiez529 commentedon Aug 30, 2026
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
TurnStartResponsereturned bystart_turnand makessend_message_to_threadreturn:{"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
turnIdassertion.Verification completed:
git diff --check/ staged-diff checks passed.gpt-5.6-terra, high) completed with no findings.just fmtorjust test -p codex-tuicommands on this host because neither the Rust toolchain norjustis 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 towait_threads, so that remaining half of exact completion tracking is still open.rtol5 commentedon Sep 30, 2026
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.
rtol5 commentedon Sep 30, 2026
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.