Repository navigation
[macOS Desktop] Automatic compaction stalls with WebSocket idle timeout; persists after app restart #42896
Description
What version of the Codex App are you using?
Installed desktop bundle inspected after the incident: 26.901.41123 (build 7942), bundle identifier com.openai.codex. The installed application is named ChatGPT and the affected surface is its Codex task UI. This is installed-bundle evidence, not a separate confirmation of the build loaded at the start of the affected turn.
What subscription do you have?
Not included in this report.
What platform is your computer?
macOS / Darwin 25.6.0, arm64.
What issue are you seeing?
A long-running Codex task remains in automatic context compaction and reconnect attempts without delivering further task output. I waited more than twenty minutes and restarted the desktop app, but the problem persisted. The waiting duration and unsuccessful restart are my observations, not a controlled timing measurement.
The visible activity sequence was:
Ran command
Success
Context automatically compacting
Reconnecting 2/2
stream disconnected before completion: idle timeout waiting for websocket
The preceding shell command was shown as successful. The connection error appeared afterward, while the UI showed automatic context compaction. This does not establish that the shell command or any particular script caused the failure.
A read-only native task status check during the incident still returned active / inProgress with a null terminal error and no new message or tool marker in the latest attempt. This conflicts with using the running indicator as evidence of productive progress; it does not establish that execution has recovered.
I also opened Voice in the affected task and it appeared to be waiting. I have not established whether Voice is relevant to the underlying failure.
What steps can reproduce the bug?
Observed sequence, not a deterministic minimal reproduction:
- Run a long Codex task until automatic context compaction starts.
- Observe prolonged compaction followed by reconnect attempts and the WebSocket idle-timeout error above.
- Wait for recovery; no further task result was confirmed during the observation.
- Restart the desktop app and reopen the same task; the problem remains visible.
The screenshot documenting the error was taken September 4, 2026 at approximately 20:33 EDT (September 5 at 00:33 UTC). It is intentionally not attached because it contains private task content.
The task composer displayed GPT-6 Astra / Max. That is a UI observation, not independent runtime attribution or evidence that the model caused the failure.
Troubleshooting attempted after the initial report
After restarting the desktop app did not resolve the visible stall, I tried the following in the affected task:
- Used Clear on the Goal.
- Used Stop on the running task.
- Requested manual context compaction to see whether it could complete.
I still do not see progress after these steps. This is my current observation; successful manual compaction or recovery has not been confirmed.
Read-only native inspection confirmed that the preceding attempt became interrupted. A subsequent attempt appears as inProgress, with a null terminal error and no latest assistant message or tool marker exposed in the status snapshot. The most recent check was at 2026-09-04 20:50:23 EDT (UTC-0400) / 2026-09-05 00:50:23 UTC. These fields do not independently confirm that Goal clearance succeeded, that the later attempt is the manual compaction operation, or that useful execution has resumed.
The inspection did not restart or resume the stopped drafting task. The unresolved issue is whether compaction can finish and provide an accurate, actionable recovery state after these manual controls.
What is the expected behavior?
Automatic compaction should complete and continue the existing task, or report a clear recoverable failure. If a stream times out, the UI should distinguish actual execution from reconnecting or failed recovery and expose a supported way to continue the same task without losing its completed work or duplicating actions.
Uploaded performance trace
The app displayed Performance trace uploaded and supplied this Feedback ID:
01a06eb8-7aa2-7981-a85f-9f95ea5da9f4
Please correlate the uploaded trace with the compaction and reconnection interval. The upload confirmation does not establish that engineering has reviewed the trace.
Related reports and diagnostic limits
- Repeated
idle timeout waiting for websocketdisconnects within a single Codex task #27625 reports the same WebSocket idle-timeout wording and repeated desktop reconnects on an older version. - Regression after unified desktop rollout: Responses WebSocket timeouts and stream disconnects #36059 reports broader desktop stream reliability failures.
- Agent often stops after compaction instead of continuing the active task #42693, opened September 4, concerns failure to continue after compaction; its reported behavior differs from remaining stuck during compaction.
This report adds the current compaction-stage stall, persistence after my app restart, native status discrepancy, and uploaded trace. A shared root cause with those reports is not established.
OpenAI Status displayed fully operational when checked around 20:34 EDT. No general outage, network cause, or model-specific regression is asserted.
No private documents, task prompts, local paths, credentials, raw logs, or screenshots are attached.
Activity
axeronta commentedon Sep 5, 2026
Additional Windows incident: stalled compaction/reconnection and failed same-task recovery
Reporting a separate Windows incident on 5 September 2026. This adds platform/version details, measured interrupted-turn durations, recorded context usage, and a successful fresh-task recovery. A shared underlying cause with the original macOS report is not established.
Environment
26.901.5280.0(package inspection; not copied from the About dialog).0.153.0, originatorCodex Desktop.10.0.26200.gpt-6-astra; the final recovery attempt retainedxhighreasoning. No model-specific cause is asserted.Observed failure
A long, tool-heavy local task stopped making visible progress. The UI repeatedly showed:
After interruptions and further prompts, the task continued to appear working without returning a useful response. One recovery run initially acknowledged the request and completed a shell command, then stopped progressing around the compaction/reconnection stage.
A read-only task inspection initially found it idle with recent turns marked interrupted. A deliberately small recovery prompt was then submitted through the app's task messaging interface: give a short acknowledgement, check that one saved checkpoint exists, and stop without restarting the long investigation. The request was accepted, but subsequent snapshots showed
active/inProgress,error: null, and no latest assistant message or tool marker.Measured timeline (UTC, 2026-09-05)
These are turn durations, not measurements of time spent exclusively in compaction. The long productive investigation before this interval is intentionally excluded.
The local app continued answering task read/list/status requests in milliseconds during the stall. A shell read could independently access the saved project checkpoints. Those facts distinguish a nonresponsive task from a confirmed whole-app or filesystem freeze; they do not diagnose the remote service.
Context and usage concern
Two recorded token-count events near the failure were:
The session reported
model_context_window: 828400. The local rollout was about 27 MB at inspection.The user reports substantial wasted time and tokens from repeated failed recovery and reconstruction. The values above are recorded request token fields, not a calculation of wasted or billable usage. Cached input is a subset of input and must not be double-counted. The failed compaction attempts' actual accounting is not visible in these observations. Please investigate server-side retry/compaction usage attribution and whether affected usage can be restored under the applicable support policy.
Recovery attempted and result
The new task responding is a verified recovery of the workflow, not evidence that the original task was repaired. No transcript/database edits or project deletion were needed.
Expected behavior
Compaction should complete or produce a bounded, actionable failure. A task that cannot recover should expose a clear state and a supported way to continue from saved work. The UI should distinguish actual task progress from compaction/reconnection waiting, and failed retries should have transparent usage accounting.
Correlation and privacy
Affected local task ID:
01a06f59-bdbe-7543-8e20-68809e1defdd.Minimal recovery turn ID:
01a070f0-984c-7001-8c75-632fe64b25c0.These are local task/turn identifiers, not an uploaded feedback or performance-trace ID. No trace upload or internal support case creation is claimed. Private project text, local usernames/paths, screenshots, raw session logs, and credentials are omitted.
easyvibecoding commentedon Sep 5, 2026
Additional evidence: compaction retry amplification in 0.153.4, spontaneous HTTP recovery, and a no-subagent protocol reproducer
Adding a separate macOS observation and controlled reproduction to this issue rather than opening a duplicate. The observation overlaps this report; it does not establish that every incident in this thread has the same upstream cause.
Environment
rust-v0.153.4, commit3d2ee51ca2d5db578f328aa75e20aa22c0197c9a. This was also the latest stable GitHub release when checked for this report.Observed recovery timeline, with identifying information removed
A tool-heavy task entered
run_auto_compact{reason=ContextLimit phase=MidTurn}. The task initially looked stuck while subagent completion notifications continued. It later recovered without interruption, another prompt, configuration changes, or app restart during this incident.Times below are relative to the last pre-compaction model token-count event; this baseline is not a direct measurement of server inference start.
idle timeout waiting for websocket; compaction retry1/22/2falling back to HTTP200 OK; compaction is still pendingcompactedrecord is persisted; window number advancesSanitized log fields:
The successful compaction records
input_tokens=205015,cached_input_tokens=204928,output_tokens=8708. The HTTP request-to-compaction-completion interval was approximately 336.7s. These are recorded successful-request values, not a calculation of failed-request or billable usage.For comparison, the same task's three earlier successful compactions took approximately 190.8s, 219.0s, and 295.8s from the preceding model event, producing 5,202, 6,140, and 7,697 output tokens. Increasing summary generation time crossing the 300s idle threshold is a plausible explanation, but those intervals include client/routing work and are not server-side inference timings.
Controlled experiment: no subagents required
I reproduced the client failure/retry/fallback mechanism with the installed 0.153.4 binary, a loopback-only synthetic HTTP/WS server, fresh temporary Codex homes, ephemeral test threads, and no subagents or copied credentials. No real conversation is replayed upstream.
The fixture uses
thread/compact/startto reach the same remote-compaction-v2 streaming/retry code. It does not reproduce the entire production automaticContextLimittrigger or its payload. To make the experiment fast, the idle timeout is 1s; the slow fixture takes 1.6s to produce a valid compaction item andresponse.completed. HTTP/SSE sends a small application event every 150ms while waiting. WS either stays silent, sends the same JSON event, or sends native protocol Ping frames.Observed results from the exact publicly included script:
All five cases completed and all sequence assertions passed. The native-Ping case sent 21 protocol Ping frames across its WS attempts and still followed the three-WS-then-HTTP path. The silent and native-Ping cases emit:
Thus a JSON application heartbeat and a WebSocket protocol Ping are not equivalent for this watchdog. The HTTP comparison includes application events; it does not show that HTTP can wait indefinitely with no events.
Source-level explanation
WsStream's message receiver: responses_websocket.rs:87–104.ws_stream.next(): responses_websocket.rs:705–724. The error establishes inactivity at this upper receive layer, not necessarily a completely silent network socket.2/2therefore is not the end of the complete transport-recovery sequence.Subagent notifications are queued by session/handlers.rs:81 and session/input_queue.rs:122. The compaction request uses a cloned history/fixed prompt. The production queued messages were consumed after compaction succeeded. Together with the no-subagent fixture, this means concurrent subagents are not necessary to reproduce the retry amplification; it does not exclude workload size or backend concurrency as contributing factors in a real task.
Possible fixes to evaluate
2/2should not imply that no further recovery phase remains.Suggested regression coverage: slow-but-live compaction with application heartbeats; native Ping/Pong without application events; truly silent/dead streams; compaction-specific fallback; cancellation; no duplicate/partially installed compaction results; and subagent messages arriving during the wait without loss or replay.
These are proposed fixes, not a production patch or a claim that forcing HTTP permanently fixes every related stall. In particular, the synthetic custom-provider configuration below is not a claim that the desktop's built-in
openaiprovider supports the same user override.Real incident correlation identifiers
Included with the reporter's explicit authorization to help server-side correlation:
01a070b1-ed7c-76e2-bc69-4a4f4fac6e5901a070b1-eee3-7570-aa8e-03768fb659b6resp_009d44e1b8826573016a9c03882e5487d0a97be3306a94573cThese are task/turn/response identifiers, not uploaded feedback or performance-trace IDs. No private conversation or trace upload is being shared by this comment.
Limits and privacy
The real incident's upstream reason for the long gap remains unconfirmed: slow generation without surfaced heartbeat, a proxy/transport delivery problem, and related service behavior need server-side request traces to distinguish. No raw wire trace was available. This report establishes the client mechanism and actual later recovery, not a definitive diagnosis of OpenAI's internal service.
Other than the three explicitly authorized correlation identifiers above, the report omits runtime identifiers, CF-Ray values, exact incident timestamps, usernames, project names, local paths, conversation content, screenshots, complete logs, account identifiers, and credentials. Only relative timings, relevant versions, selected diagnostic fields, aggregate token counts, and synthetic reproduction code/results are included. No private trace upload or support-case creation is claimed.
Related: #39771 discusses the distinction between model silence and protocol liveness; #38638 discusses retry latency and transport fallback. This adds compaction-v2-specific evidence and a fast, isolated reproducer on 0.153.4.
Standalone synthetic reproducer (Python; five cases and assertions)
Requirements: Python 3.10+,
aiohttp, andzstandard. Run in a disposable local test directory. Put the desiredcodexexecutable on PATH or setCODEX_BINARYto it. The script starts only a loopback model endpoint and uses fresh temporary Codex state; it never copies an auth file or credential environment variable.smixs commentedon Sep 13, 2026
Подтверждаю два случая на macOS с проверкой границы, на которой останавливается работа. Добавляю к этому issue, поскольку совпадают зависание компактации, WebSocket timeout/reset и отсутствие надёжного продолжения после перезапуска.
Первый случай: 5–6 сентября 2026 года
26.901.41123, build7942.codex-cli 0.153.3. Отдельно установленный CLI имел другую версию и не обслуживал эту задачу.26.6.2, arm64; ChatGPT-аутентификация;gpt-6-astra, reasoninghigh.244800; полное окно:258400токенов.Сначала одна автоматическая компактация успешно завершилась: после неё журнал показывал около 49 878 токенов контекста. После повторного накопления контекста следующая компактация перестала завершаться.
Все времена UTC:
remote compaction v2 stream failed; retrying request after delay,retries=1 max_retries=2,idle timeout waiting for websocket.retries=2 max_retries=2.compactedне появился.Типичная ошибка:
WebSocket успешно устанавливался и переустанавливался. Между неудачными компактациями короткие обычные ответы в этой же задаче могли завершаться. Это сужает наблюдаемую проблему до пути компактации, но не доказывает конкретную серверную или клиентскую первопричину.
Сохранённый исходный журнал: 1 040 корректных JSONL-записей, 17 597 112 байт, одна успешная компактация. Исследование не обнаружило в сохранённых предупреждениях/ошибках этой задачи 401, 429 или сообщения о повреждении SQLite.
После сохранения исходного журнала был выполнен отдельный ограниченный тест того же движка с
remote_compaction_v2=false. Это не оказалось рабочим восстановлением:thread/compact/startобратился к старому маршруту и немедленно получил:Изменение флага было ограничено диагностическим процессом; глобальная конфигурация не изменялась. Не предлагаю отключение v2 как обходной путь.
Второй случай: 13 сентября 2026 года
26.908.40834, build8881; метаданные сессии0.154.0-alpha.6.2, журналы рабочего процесса также указывают0.154.0.27.0(26A428), arm64;gpt-6-astra,xhigh.В 03:16:16 UTC, сразу после завершённого вызова инструмента, начался
run_auto_compact{reason=ContextLimit phase=MidTurn}: 247 167 токенов при пороге 244 800.В 03:18:34 UTC:
Последующие попытки снова попадали в
run_pre_sampling_compact/phase=PreTurnперед ответом. Во время проверки интерфейсный статус оставалсяactive/inProgress, сerror=null, без нового сообщения или инструмента.В отличие от первого случая, 13 сентября восстановление в итоге произошло: событие
compactedсохранено в 03:24:57.209 UTC, после последующих действий пользователя задача продолжила работу. Это примерно 8 минут 41 секунда от первого старта компактации до успешного события, включая прерывания и повторные попытки, а не длительность одного запроса. Не утверждаю, что этот случай был необратимым зависанием.Позже в этой же задаче возникла другая проблема: завершённые команды оставались визуально работающими, а часть истории исчезла после повторного открытия. Детали добавлены в #42311. Совпадение в одной задаче не доказывает общую причину с транспортным сбоем.
Просьба к разработчикам
Нужны ограниченное по времени восстановление компактации, точное отображение состояния ожидания/ошибки и поддерживаемый путь продолжения существующей задачи. Перезапуск и повторное «продолжай» не должны оставлять пользователя в цикле той же компактации без понятного результата. Также нужен рабочий поддерживаемый вариант восстановления, когда v2 повторно истекает по таймауту, а прежний endpoint возвращает 404.
Это технические выдержки из двух локально исследованных случаев. Полная переписка, исходные журналы, идентификаторы задач, частные пути и учётные данные не публикуются. Модель, сеть или один конкретный компонент Codex не объявляются установленной первопричиной.
HonkCY commentedon Sep 14, 2026
This is still happening on Codex Desktop 26.908.40834 on macOS.
Automatic compaction gets stuck indefinitely at “Optimizing conversation”. I’m currently watching it sit there for minutes with no useful progress and no actionable error state. This is not an edge-case cosmetic bug. Compaction is on the critical path of long-running Codex work, so when it hangs, the entire thread becomes unusable.
The reliability of Codex Desktop is frankly unacceptable for a paid development tool. I encounter workflow-breaking issues like this constantly. A coding agent cannot be considered reliable if basic session lifecycle operations such as compaction can silently hang and force users to abandon or reconstruct active work.
Please stop presenting an indefinite spinner as “working”. At minimum:
I should not have to treat every long Codex thread as disposable because the harness may randomly wedge itself.
yuchisong commentedon Oct 3, 2026
I hit similar compaction/reconnection symptoms on October 3, 2026, using the Codex extension in VS Code on a MacBook Pro. This issue is about the desktop app, so I'm not sure whether the extension case has the same cause.
The UI showed compaction, then "Reconnecting 2/2", followed by:
stream disconnected before completion: idle timeout waiting for websocket
The "Working" timer showed roughly 5 hours 48 minutes, but I can't tell how much of that was productive execution versus waiting. A subsequent prompt asking for status also received no response. I restarted VS Code; recovery after the restart hasn't been confirmed. Exact macOS, VS Code, and extension versions are not available for this report yet.
The practical impact is that an unattended workflow appeared to remain active without delivering a response or a clear recovery state. Could you triage whether this belongs with this bug or should be filed as a separate VS Code extension issue?