Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6834: fix(codex): preserve token usage on cancelled turns (#7753)
mrlonely074f5ab237f1
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex f13066623b..a0c787e38e 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -255,6 +255,7 @@ Daemon behavior is configured via flags or environment variables:| Codex semantic inactivity timeout | `--codex-semantic-inactivity-timeout` | `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as the idle watchdog (Codex's timer is not tool-aware, so it tracks the larger of the idle / tool budgets) || Codex first-turn no-progress timeout | — | `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` (keeps the built-in `60s` ceiling) || Codex handshake timeout | `--codex-handshake-timeout` | `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`; `thread/start` and `thread/resume`: `60s` (an explicit value overrides both budgets globally) |+| Codex turn-interrupt timeout | — | `MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT` | `2s` (bounded grace period for `turn/interrupt` acknowledgement and `turn/completed`; tune from the logged interrupt latency on unusually slow hosts) || OpenCode idle watchdog | — | `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` (`0` falls back to the generic idle watchdog; cannot extend it) || Max concurrent tasks | `--max-concurrent-tasks` | `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` || Daemon ID | `--daemon-id` | `MULTICA_DAEMON_ID` | hostname |diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 64c5bc8f99..8a8d19d18d 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -239,6 +239,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | Codex のセマンティック静穏しきい値。Codex 自身のタイマーはツール実行中かどうかを判別できないため、独自の短い上限を持たず idle / tool 予算の大きい方に追従します || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 初回ターンの無進捗上限を明示的に上書き;`0` はデフォルトを維持。実効の初回ターン待機は依然として `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` と全体の実行タイムアウトに制限される——`MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` をこの値より厳密に大きく(余裕を持たせて)設定すること。さもないと待機はその値で打ち切られ、モデルカタログの起動リトライがスキップされる。同値では不十分:セマンティックタイマーが先に起動するため、同値の場合でもリトライが失われることがある || `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`、`thread/start`・`thread/resume`:`60s` | Codex app-server 起動ハンドシェイクの上限。明示的な値は両方の予算を一括で上書きします |+| `MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT` | `2s` | キャンセル後に Codex app-server が `turn/interrupt` を確認し `turn/completed` を送信するまでの猶予時間。プロセスを強制終了する前に最終トークン使用量を保持します。特に遅いホストでは daemon ログに記録された割り込み遅延を基に調整できます || `MULTICA_DAEMON_AUTO_UPDATE` | Cloud は `true`、セルフホストは `false` | CLI の更新を自動でチェックして適用するか || `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 更新チェックの間隔 || `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 帯域外で置き換えられた `multica` バイナリ(`brew upgrade`、再ダウンロード、ローカルビルド)へ再起動して追従するかどうか。`MULTICA_DAEMON_AUTO_UPDATE` とは独立 |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex ac2805136f..856c2603b2 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -239,6 +239,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | Codex 의미 활동 없음 기준값. Codex 자체 타이머는 도구 실행 중인지 알 수 없으므로 별도의 짧은 상한 대신 idle / tool 예산 중 큰 값을 따릅니다 || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 첫 턴 무진행 상한의 명시적 재정의; `0` 은 기본값 유지. 실제 첫 턴 대기는 여전히 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 및 전체 실행 타임아웃으로 제한됨 — `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 을 이 값보다 엄격히 크게(여유를 두고) 설정해야 하며, 그렇지 않으면 대기가 그 값으로 잘리고 모델 카탈로그 시작 재시도가 건너뛰어짐. 값이 같으면 충분하지 않음: 의미 타이머가 먼저 시작되므로 값이 같을 때도 재시도가 손실될 수 있음 || `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`, `thread/start`·`thread/resume`: `60s` | Codex app-server 시작 handshake 상한. 명시적으로 설정한 값은 두 예산을 모두 일괄 재정의합니다 |+| `MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT` | `2s` | 취소 후 Codex app-server가 `turn/interrupt`를 확인하고 `turn/completed`를 보낼 때까지의 유예 시간입니다. 프로세스를 강제 정리하기 전에 최종 토큰 사용량을 보존합니다. 특히 느린 호스트에서는 daemon 로그에 기록된 인터럽트 지연을 기준으로 조정할 수 있습니다 || `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`, 자체 호스팅 `false` | CLI 자동 확인 및 업데이트 여부 || `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 업데이트 확인 간격 || `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 외부에서 교체된 `multica` 바이너리(`brew upgrade`, 재다운로드, 로컬 빌드)로 재시작할지 여부. `MULTICA_DAEMON_AUTO_UPDATE`와 독립적 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex fc593ee590..62f2bdf9b5 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -239,6 +239,7 @@ The variables below are read on the computer that runs your agents, not in the A| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Codex semantic-silence threshold. Codex's own timer cannot see that a tool is running, so it tracks the larger of the idle / tool budgets instead of holding a separate, shorter ceiling || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Explicit override for the Codex first-turn no-progress ceiling; `0` keeps the default. The effective first-turn wait stays bounded by `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` and the overall execution timeout — set `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` strictly above this value (with some margin), or the wait is truncated to it and the model-catalog startup retry is skipped. Equal values are not enough: the semantic timer is armed first, so at equal durations the retry can still be lost || `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`; `thread/start`, `thread/resume`: `60s` | Codex app-server startup handshake ceilings. An explicit value overrides both budgets globally |+| `MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT` | `2s` | Grace period after cancellation for Codex app-server to acknowledge `turn/interrupt` and emit `turn/completed`, preserving final token usage before forced process cleanup. On unusually slow hosts, tune this from the interrupt latency recorded in daemon logs || `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`; self-hosted `false` | Whether to check for and apply CLI updates automatically || `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | Update check interval || `MULTICA_DAEMON_AUTO_RELOAD` | `true` | Whether to restart into a `multica` binary replaced on disk out of band (`brew upgrade`, a re-download, a local build). Independent of `MULTICA_DAEMON_AUTO_UPDATE` |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 9cc2ede491..b40c2c5aef 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -239,6 +239,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | Codex 语义静默阈值。Codex 自己的计时器看不到工具是否在执行,因此跟随 idle / tool 预算中较大的那个,而不再单独保留一个更短的上限 || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | 显式覆盖 Codex 首轮无进展上限;`0` 保持默认值。实际首轮等待仍受 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 和总执行超时限制——需将 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 设为严格大于此值(并留出余量),否则等待会被截断至该值,且会跳过模型目录启动重试。设为相等还不够:语义计时器先启动,两者相等时仍可能丢失该重试 || `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`;`thread/start`、`thread/resume`:`60s` | Codex app-server 启动握手上限;显式设置后会统一覆盖两类预算 |+| `MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT` | `2s` | 任务取消后等待 Codex app-server 确认 `turn/interrupt` 并发出 `turn/completed` 的宽限期,以便在强制清理进程前保留最终 token 用量。主机异常缓慢时,可根据 daemon 日志记录的中断延迟调整 || `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`;自托管 `false` | 是否自动检查并更新 CLI || `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 检查更新的间隔 || `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 是否在 `multica` 二进制被带外替换(`brew upgrade`、重新下载、本地构建)后重启到新二进制。与 `MULTICA_DAEMON_AUTO_UPDATE` 相互独立 |diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 833cf5da14..1ddcd0fe05 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -34,6 +34,7 @@ const (DefaultAgentTimeout = 0DefaultCodexSemanticInactivityTimeout = 10 * time.MinuteDefaultCodexHandshakeTimeout = 30 * time.Second+ DefaultCodexTurnInterruptTimeout = 2 * time.SecondDefaultCodexThreadHandshakeTimeout = 60 * time.Second// DefaultOpenCodeIdleWatchdog shortens the no-message budget for OpenCode// runs while they are not executing a tool. OpenCode streams text and tool@@ -140,15 +141,20 @@ type Config struct {// for app-servers that are legitimately slow to their first event (GH #3262).CodexFirstTurnNoProgressTimeout time.DurationCodexHandshakeTimeout time.Duration- CodexThreadHandshakeTimeout time.Duration- OpenCodeIdleWatchdog time.Duration // OpenCode-specific no-message window; 0 falls back to AgentIdleWatchdog and values above it cannot extend the global bound- AgentIdleWatchdog time.Duration // force-stop a run when the backend goes silent this long with an empty queue (0 = disabled)- AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = never force-stop during a tool call); defaults to AgentIdleWatchdog, so operators tune one number unless they deliberately want a wider tool budget- ClaudeArgs []string- CodexArgs []string- CodebuddyArgs []string- QwenArgs []string- QwenpawArgs []string+ // CodexTurnInterruptTimeout is the bounded grace period after cancellation+ // for app-server to acknowledge turn/interrupt and emit turn/completed.+ // Operators can tune it with MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT using the+ // latency recorded in the Codex lifecycle logs.+ CodexTurnInterruptTimeout time.Duration+ CodexThreadHandshakeTimeout time.Duration+ OpenCodeIdleWatchdog time.Duration // OpenCode-specific no-message window; 0 falls back to AgentIdleWatchdog and values above it cannot extend the global bound+ AgentIdleWatchdog time.Duration // force-stop a run when the backend goes silent this long with an empty queue (0 = disabled)+ AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = never force-stop during a tool call); defaults to AgentIdleWatchdog, so operators tune one number unless they deliberately want a wider tool budget+ ClaudeArgs []string+ CodexArgs []string+ CodebuddyArgs []string+ QwenArgs []string+ QwenpawArgs []string// ProfileCommandOverrides maps a custom runtime profile_id -> the absolute// executable path to use for that profile on THIS machine (MUL-3284).@@ -447,6 +453,13 @@ func LoadConfig(overrides Overrides) (Config, error) {if overrides.CodexHandshakeTimeout > 0 {codexThreadHandshakeTimeout = overrides.CodexHandshakeTimeout}+ codexTurnInterruptTimeout, err := durationFromEnv("MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT", DefaultCodexTurnInterruptTimeout)+ if err != nil {+ return Config{}, err+ }+ if codexTurnInterruptTimeout <= 0 {+ codexTurnInterruptTimeout = DefaultCodexTurnInterruptTimeout+ }maxConcurrentTasks, err := intFromEnv("MULTICA_DAEMON_MAX_CONCURRENT_TASKS", DefaultMaxConcurrentTasks)if err != nil {@@ -634,6 +647,7 @@ func LoadConfig(overrides Overrides) (Config, error) {CodexSemanticInactivityTimeout: codexSemanticInactivityTimeout,CodexFirstTurnNoProgressTimeout: codexFirstTurnNoProgressTimeout,CodexHandshakeTimeout: codexHandshakeTimeout,+ CodexTurnInterruptTimeout: codexTurnInterruptTimeout,CodexThreadHandshakeTimeout: codexThreadHandshakeTimeout,OpenCodeIdleWatchdog: openCodeIdleWatchdog,AgentIdleWatchdog: agentIdleWatchdog,diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex 19471e42c6..1e7da081f9 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -728,6 +728,34 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {}}+func TestLoadConfig_CodexTurnInterruptTimeout(t *testing.T) {+ stageFakeAgent(t)+ t.Setenv("MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT", "750ms")++ cfg, err := LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with interrupt timeout: %v", err)+ }+ if cfg.CodexTurnInterruptTimeout != 750*time.Millisecond {+ t.Fatalf("CodexTurnInterruptTimeout = %s, want 750ms", cfg.CodexTurnInterruptTimeout)+ }++ t.Setenv("MULTICA_CODEX_TURN_INTERRUPT_TIMEOUT", "0")+ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with zero interrupt timeout: %v", err)+ }+ if cfg.CodexTurnInterruptTimeout != DefaultCodexTurnInterruptTimeout {+ t.Fatalf("CodexTurnInterruptTimeout = %s, want default %s", cfg.CodexTurnInterruptTimeout, DefaultCodexTurnInterruptTimeout)+ }+}+// TestLoadConfig_CodexFirstTurnNoProgressTimeout pins the env-only// MULTICA_CODEX_FIRST_TURN_TIMEOUT resolution (GH #3262 / #5959): unset and an// explicit "0" both mean "keep the backend default" (0 = unset), while a positivediff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex b3aa8a12d2..ef5ec42591 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8240,6 +8240,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iFirstTurnNoProgressTimeout: d.cfg.CodexFirstTurnNoProgressTimeout,IdleWatchdogTimeout: idleWatchdogTimeout,HandshakeTimeout: d.cfg.CodexHandshakeTimeout,+ TurnInterruptTimeout: d.cfg.CodexTurnInterruptTimeout,ThreadHandshakeTimeout: d.cfg.CodexThreadHandshakeTimeout,ResumeSessionID: task.PriorSessionID,// Post-gate intent: PriorSessionID here already reflects the pre-flightdiff --git a/server/internal/metrics/pricing.go b/server/internal/metrics/pricing.goindex 1b0a44fa2e..1ba88dab2f 100644--- a/server/internal/metrics/pricing.go+++ b/server/internal/metrics/pricing.go@@ -25,10 +25,9 @@ var modelPrices = map[string]ModelPrice{// GPT-5.6 announcement (openai.com/index/previewing-gpt-5-6-sol). For 5.6+// cache read is the 90%-off cached-input rate (0.1x input) and cache write// is billed at 1.25x the uncached input rate — unlike earlier OpenAI SKUs,- // which don't bill cache writes separately. NOTE: Codex's app-server usage- // stream (0.144.1) does not yet report cache-write tokens separately, so- // today those tokens fall into plain input and are billed at 1x; the- // CacheWrite rate below is correct but not yet exercised for Codex.+ // which don't bill cache writes separately. Codex app-server v0.147 reports+ // cache-write input separately while including it in the raw input total;+ // the collector normalizes those into mutually exclusive billing buckets."openai:gpt-5.6-sol": {Provider: "openai", Model: "gpt-5.6-sol", InputPerM: 5.00, CacheReadPerM: 0.50, CacheWritePerM: 6.25, OutputPerM: 30.00},"openai:gpt-5.6-terra": {Provider: "openai", Model: "gpt-5.6-terra", InputPerM: 2.50, CacheReadPerM: 0.25, CacheWritePerM: 3.125, OutputPerM: 15.00},"openai:gpt-5.6-luna": {Provider: "openai", Model: "gpt-5.6-luna", InputPerM: 1.00, CacheReadPerM: 0.10, CacheWritePerM: 1.25, OutputPerM: 6.00},diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 3ddb16a5e1..e4dc50c8f7 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -59,6 +59,12 @@ type ExecOptions struct {// protocol transport. It is currently consumed by Codex app-server;// zero uses the provider default rather than disabling the bound.HandshakeTimeout time.Duration+ // TurnInterruptTimeout bounds how long the Codex backend waits for the+ // app-server to acknowledge turn/interrupt and emit turn/completed after a+ // task is cancelled. Zero uses the provider default. A positive override is+ // useful on slower hosts without coupling cancellation cleanup to the much+ // longer execution or handshake budgets.+ TurnInterruptTimeout time.Duration// ThreadHandshakeTimeout optionally gives Codex's heavier thread/start and// thread/resume RPCs a wider budget than initialize and turn/start. Zero// preserves the legacy behavior for callers that explicitly setdiff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 6bdca4b4fc..e83bd856dd 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -60,6 +60,19 @@ const (// while keeping the fast-fail value (MUL-5542).defaultCodexFirstTurnNoProgressTimeout = 60 * time.SeconddefaultCodexHandshakeTimeout = 30 * time.Second+ // defaultCodexTurnInterruptTimeout gives app-server a short, bounded window to+ // finish an interrupted turn and report its final token usage before the+ // process is torn down. This mirrors the native Codex stop flow without+ // letting a wedged interrupt delay replacement executions indefinitely. The+ // value is independently configurable per execution; lifecycle logs record+ // the observed acknowledgement/completion latency so deployments can tune it+ // from their own app-server evidence. On 2026-09-01, the reproducible real-+ // agent probe in codex_interrupt_latency_integration_test.go measured 20+ // interrupted generations and 20 interrupted active tools on WSL/Linux with+ // codex-cli 0.147.0: turn/completed P99/max were 15ms/15ms and 13ms/13ms.+ // Two seconds deliberately keeps more than 130x headroom over the observed+ // worst protocol completion for host load and cross-platform scheduling.+ defaultCodexTurnInterruptTimeout = 2 * time.Second// thread/start and thread/resume may refresh the model catalog, initialize// MCP integrations, and restore persisted history. Field evidence shows// healthy calls crossing the 30s budget used for local initialize, so keep@@ -1080,7 +1093,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec})}codexArgs := buildCodexArgs(opts, b.cfg.Logger)- cmd := runtimeCmd.exec(runCtx, codexArgs...)+ // Keep the app-server alive long enough to handle turn/interrupt when the+ // task context is cancelled. The lifecycle goroutine remains governed by+ // runCtx and explicitly stops this process context during bounded cleanup.+ processCtx, stopProcess := context.WithCancel(context.WithoutCancel(runCtx))+ cmd := runtimeCmd.exec(processCtx, codexArgs...)hideAgentWindow(cmd)// Run codex in its own process group so a cancel-on-stuck cleanup// reaches the whole tree — the codex Node wrapper plus the native@@ -1114,11 +1131,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execstdout, err := cmd.StdoutPipe()if err != nil {cancel()+ stopProcess()return nil, fmt.Errorf("codex stdout pipe: %w", err)}stdin, err := cmd.StdinPipe()if err != nil {cancel()+ stopProcess()return nil, fmt.Errorf("codex stdin pipe: %w", err)}// Codex stderr can contain auth/provider diagnostics. Capture a bounded@@ -1135,6 +1154,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// cannot be resumed is killed and reported here.if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {cancel()+ stopProcess()return nil, fmt.Errorf("start codex: %w", err)}activeLaunches := activeCodexLaunches.Add(1)@@ -1287,7 +1307,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// 2. Wait for cmd.Wait() to return, capped by another// codexGracefulShutdownTimeout. Normally this returns immediately// because the process has already exited. In the stuck-child case- // the process is still alive — we cancel the runCtx, which fires+ // the process is still alive — we cancel the process context, which fires// cmd.Cancel (the group-SIGKILL helper installed above), and// cmd.WaitDelay then guarantees cmd.Wait() returns even if pipes// stay open.@@ -1326,7 +1346,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"pid", cmd.Process.Pid,"grace", grace.String(),)- cancel()+ stopProcess()// On Windows, Cancel terminates only the direct child. A// descendant may keep inherited stdout open indefinitely. Start// Wait now so os/exec's WaitDelay closes the pipe after its@@ -1356,7 +1376,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"pid", cmd.Process.Pid,"grace", grace.String(),)- cancel()+ stopProcess()// WaitDelay (10s) is the final backstop: even if the// group-kill races with an open pipe held by a// descendant, cmd.Wait() returns within WaitDelay of the@@ -1401,6 +1421,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execgo func() {defer activeCodexLaunches.Add(-1)defer cancel()+ defer stopProcess()defer close(msgCh)defer close(resCh)defer drainAndWait()@@ -1431,6 +1452,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// Kill the whole process group before waiting so a leader that exits// on stdin EOF cannot leave detached-stdio descendants behind.signalProcessGroup(cmd, syscall.SIGKILL)+ } else if runCtx.Err() != nil {+ // processCtx deliberately outlives runCtx so active turns can use+ // turn/interrupt. Initialize has no interruptible turn, so a parent+ // cancellation must take the fast process-tree cleanup path.+ stopProcess()}drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"@@ -1470,6 +1496,10 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// the whole process group before waiting so a leader that exits on// EOF cannot leave detached-stdio descendants behind.signalProcessGroup(cmd, syscall.SIGKILL)+ } else if runCtx.Err() != nil {+ // No turn exists during thread start/resume, so there is nothing to+ // interrupt and no reason to spend the graceful shutdown budget.+ stopProcess()}drainAndWait() // flush os/exec stderr goroutine before sampling TailfinalStatus = "failed"@@ -1565,18 +1595,37 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}}}+ finishRunContextDone := func() {+ waitingForTurn = false+ if runCtx.Err() == context.DeadlineExceeded {+ finishFirstItemWait("execution_timeout")+ finalStatus = "timeout"+ finalError = fmt.Sprintf("codex timed out after %s", timeout)+ } else {+ finishFirstItemWait("cancelled")+ finalStatus = "aborted"+ finalError = "execution cancelled"+ }+ }turnNotificationGate.arm()_, err = c.request(runCtx, "turn/start", turnParams)if err != nil {- select {- case aborted := <-turnDone:- finishTurn(aborted)- default:- drainAndWait() // flush os/exec stderr goroutine before sampling Tail- finalStatus = "failed"- finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}- return+ if runCtx.Err() != nil {+ finishRunContextDone()+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {+ stopProcess()+ }+ } else {+ select {+ case aborted := <-turnDone:+ finishTurn(aborted)+ default:+ drainAndWait() // flush os/exec stderr goroutine before sampling Tail+ finalStatus = "failed"+ finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(stderrBuf.Tail()))+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }}}@@ -1599,18 +1648,6 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}defer stopFirstTurnNoProgressTimer()- finishRunContextDone := func() {- waitingForTurn = false- if runCtx.Err() == context.DeadlineExceeded {- finishFirstItemWait("execution_timeout")- finalStatus = "timeout"- finalError = fmt.Sprintf("codex timed out after %s", timeout)- } else {- finishFirstItemWait("cancelled")- finalStatus = "aborted"- finalError = "execution cancelled"- }- }for waitingForTurn {select {case aborted := <-turnDone:@@ -1637,18 +1674,19 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecwaitingForTurn = falsefinishFirstItemWait("no_progress_timeout")finalStatus = "timeout"+ turnID := c.activeTurnID()timeoutDiagnostic = codexTimeoutDiagnostic{Kind: codexTimeoutFirstTurnNoProgress,Timeout: firstTurnNoProgressTimeout,LastActivity: lastSemanticActivityDescription,ThreadID: threadID,- TurnID: c.turnID,+ TurnID: turnID,Model: opts.Model,}b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,"pid", cmd.Process.Pid,"thread_id", threadID,- "turn_id", c.turnID,+ "turn_id", turnID,"timeout", firstTurnNoProgressTimeout.String(),"last_activity", lastSemanticActivityDescription,)@@ -1656,24 +1694,28 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecwaitingForTurn = falsefinishFirstItemWait("semantic_inactivity_timeout")finalStatus = "timeout"+ turnID := c.activeTurnID()timeoutDiagnostic = codexTimeoutDiagnostic{Kind: codexTimeoutSemanticInactivity,Timeout: semanticInactivityTimeout,LastActivity: lastSemanticActivityDescription,ThreadID: threadID,- TurnID: c.turnID,+ TurnID: turnID,Model: opts.Model,}b.cfg.Logger.Warn(CodexSemanticInactivityMarker,"pid", cmd.Process.Pid,"thread_id", threadID,- "turn_id", c.turnID,+ "turn_id", turnID,"timeout", semanticInactivityTimeout.String(),"last_activity", lastSemanticActivityDescription,"idle_for", time.Since(lastSemanticActivity).Round(time.Millisecond).String(),)case <-runCtx.Done():finishRunContextDone()+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {+ stopProcess()+ }case <-c.processDone:select {case aborted := <-turnDone:@@ -1754,7 +1796,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"active_launches", activeLaunches,"method", "turn/start","thread_id", threadID,- "turn_id", c.turnID,+ "turn_id", c.activeTurnID(),"outcome", outcome,"latency", waitLatency.Round(time.Millisecond).String(),"latency_ms", waitLatency.Milliseconds(),@@ -2256,6 +2298,7 @@ type codexClient struct {threadSetupMethod stringthreadSetupStarted time.TimethreadID string+ turnIDMu sync.RWMutexturnID stringonMessage func(Message)onSemanticActivity func(description string)@@ -2280,6 +2323,11 @@ type codexClient struct {usageMu sync.Mutexusage TokenUsage // accumulated from turn events+ // usageTotal is the last accepted cumulative v2 usage snapshot for the+ // active turn. Comparing later snapshots against it makes replay and+ // duplicate delivery idempotent while retaining multi-response turns.+ usageTotal codexRawTokenUsage+ usageTotalSet boolturnErrorMu sync.MutexturnError string // captured from turn/completed status=failed or terminal error notifications@@ -2368,6 +2416,21 @@ func (c *codexClient) getTurnError() string {return c.turnError}+func (c *codexClient) setActiveTurnID(turnID string) {+ if turnID == "" {+ return+ }+ c.turnIDMu.Lock()+ c.turnID = turnID+ c.turnIDMu.Unlock()+}++func (c *codexClient) activeTurnID() string {+ c.turnIDMu.RLock()+ defer c.turnIDMu.RUnlock()+ return c.turnID+}+type pendingRPC struct {ch chan rpcResultmethod string@@ -2424,6 +2487,55 @@ func codexRequestContextError(ctx context.Context) error {return ctx.Err()}+// interruptCodexTurn follows the app-server's native stop protocol before the+// cancelled execution tears down its process. Current app-server versions emit+// final usage in thread/tokenUsage/updated immediately before turn/completed,+// so an immediate process-group SIGKILL loses otherwise valid local token+// accounting for cancelled/replaced tasks. The bool reports whether the turn+// reached that authoritative completion boundary; callers must force-stop the+// process tree when it is false.+func interruptCodexTurn(c *codexClient, threadID string, turnDone <-chan bool, configuredTimeout time.Duration, logger *slog.Logger) bool {+ select {+ case <-turnDone:+ // Completion won the cancellation race; usage has already been captured.+ return true+ default:+ }++ turnID := c.activeTurnID()+ if threadID == "" || turnID == "" {+ return false+ }+ if logger == nil {+ logger = slog.Default()+ }+ interruptTimeout := configuredTimeout+ if interruptTimeout <= 0 {+ interruptTimeout = defaultCodexTurnInterruptTimeout+ }+ started := time.Now()++ interruptCtx, cancelInterrupt := context.WithTimeout(context.Background(), interruptTimeout)+ defer cancelInterrupt()+ _, err := c.request(interruptCtx, "turn/interrupt", map[string]any{+ "threadId": threadID,+ "turnId": turnID,+ })+ if err != nil {+ logger.Warn("codex turn interrupt failed", "thread_id", threadID, "turn_id", turnID, "error", err, "latency", time.Since(started).Round(time.Millisecond).String(), "timeout", interruptTimeout.String())+ return false+ }++ select {+ case <-turnDone:+ logger.Info("codex turn interrupted", "thread_id", threadID, "turn_id", turnID, "latency", time.Since(started).Round(time.Millisecond).String(), "timeout", interruptTimeout.String())+ return true+ case <-interruptCtx.Done():+ logger.Warn("codex turn interrupt completion timed out", "thread_id", threadID, "turn_id", turnID, "latency", time.Since(started).Round(time.Millisecond).String(), "timeout", interruptTimeout.String())+ return false+ }+}+func (c *codexClient) request(ctx context.Context, method string, params any) (json.RawMessage, error) {if err := ctx.Err(); err != nil {return nil, err@@ -3230,9 +3342,12 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any}switch method {+ case "thread/tokenUsage/updated":+ c.updateThreadTokenUsage(params)+case "turn/started":if turnID := extractNestedString(params, "turn", "id"); turnID != "" {- c.turnID = turnID+ c.setActiveTurnID(turnID)}if c.onMessage != nil {c.onMessage(Message{Type: MessageStatus, Status: "running", SessionID: c.threadID})@@ -3407,6 +3522,56 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an}}+// updateThreadTokenUsage consumes the v2 app-server's real usage notification.+// Resume can replay a historical snapshot after thread/resume returns, so only+// notifications attributed to the active turn are eligible. The first current-+// turn snapshot contributes `last`; later snapshots contribute the monotonic+// delta from `total`. This retains multi-response tool loops without charging+// replayed history or duplicate snapshots twice.+func (c *codexClient) updateThreadTokenUsage(params map[string]any) {+ turnID, _ := params["turnId"].(string)+ if turnID == "" || turnID != c.activeTurnID() {+ return+ }++ tokenUsage, ok := params["tokenUsage"].(map[string]any)+ if !ok {+ return+ }+ totalMap, ok := tokenUsage["total"].(map[string]any)+ if !ok {+ return+ }+ last, ok := tokenUsage["last"].(map[string]any)+ if !ok {+ return+ }++ total := codexRawTokenUsageFromV2(totalMap)+ delta := codexRawTokenUsageFromV2(last)+ c.usageMu.Lock()+ if c.usageTotalSet {+ delta = subtractCodexRawTokenUsage(total, c.usageTotal)+ }+ c.usageTotal = total+ c.usageTotalSet = true+ c.usage.InputTokens += codexPlainInputTokens(delta.InputTokens, delta.CachedInputTokens, delta.CacheWriteInputTokens)+ c.usage.OutputTokens += delta.OutputTokens + delta.ReasoningOutputTokens+ c.usage.CacheReadTokens += delta.CachedInputTokens+ c.usage.CacheWriteTokens += delta.CacheWriteInputTokens+ c.usageMu.Unlock()+}++func codexRawTokenUsageFromV2(usage map[string]any) codexRawTokenUsage {+ return codexRawTokenUsage{+ InputTokens: codexInt64(usage, "inputTokens"),+ OutputTokens: codexInt64(usage, "outputTokens"),+ CachedInputTokens: codexInt64(usage, "cachedInputTokens"),+ CacheWriteInputTokens: codexInt64(usage, "cacheWriteInputTokens"),+ ReasoningOutputTokens: codexInt64(usage, "reasoningOutputTokens"),+ }+}+func isCodexItemProgressActivity(method string) bool {return strings.HasPrefix(method, "item/")}@@ -3458,6 +3623,15 @@ func codexUncachedInputTokens(inputTokens, cachedInputTokens int64) int64 {return uncached}+// codexPlainInputTokens removes both cache details from Codex's raw input+// total, which includes cache-read and cache-write input in v2 and JSONL usage.+func codexPlainInputTokens(inputTokens, cacheReadTokens, cacheWriteTokens int64) int64 {+ return codexUncachedInputTokens(+ codexUncachedInputTokens(inputTokens, cacheReadTokens),+ cacheWriteTokens,+ )+}+// codexInt64 returns the first non-zero int64 value from the map for the given keys.func codexInt64(m map[string]any, keys ...string) int64 {for _, key := range keys {@@ -3651,6 +3825,7 @@ type codexRawTokenUsage struct {OutputTokens int64 `json:"output_tokens"`CachedInputTokens int64 `json:"cached_input_tokens"`CacheReadInputTokens int64 `json:"cache_read_input_tokens"`+ CacheWriteInputTokens int64 `json:"cache_write_input_tokens"`ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`}@@ -3751,11 +3926,13 @@ func parseCodexSessionFileSince(path string, startTime time.Time, resumed bool)if !finalUsageFound {return nil}- cachedTokens := finalUsage.CachedInputTokens+ cacheReadTokens := finalUsage.CachedInputTokens+ cacheWriteTokens := finalUsage.CacheWriteInputTokensresult.usage = TokenUsage{- InputTokens: codexUncachedInputTokens(finalUsage.InputTokens, cachedTokens),- OutputTokens: finalUsage.OutputTokens + finalUsage.ReasoningOutputTokens,- CacheReadTokens: cachedTokens,+ InputTokens: codexPlainInputTokens(finalUsage.InputTokens, cacheReadTokens, cacheWriteTokens),+ OutputTokens: finalUsage.OutputTokens + finalUsage.ReasoningOutputTokens,+ CacheReadTokens: cacheReadTokens,+ CacheWriteTokens: cacheWriteTokens,}return &result}@@ -3770,6 +3947,7 @@ func subtractCodexRawTokenUsage(total, baseline codexRawTokenUsage) codexRawTokeInputTokens: nonNegativeTokenDelta(total.InputTokens, baseline.InputTokens),OutputTokens: nonNegativeTokenDelta(total.OutputTokens, baseline.OutputTokens),CachedInputTokens: nonNegativeTokenDelta(total.CachedInputTokens, baseline.CachedInputTokens),+ CacheWriteInputTokens: nonNegativeTokenDelta(total.CacheWriteInputTokens, baseline.CacheWriteInputTokens),ReasoningOutputTokens: nonNegativeTokenDelta(total.ReasoningOutputTokens, baseline.ReasoningOutputTokens),}}@@ -3787,6 +3965,7 @@ func addCodexRawTokenUsage(a, b codexRawTokenUsage) codexRawTokenUsage {InputTokens: a.InputTokens + b.InputTokens,OutputTokens: a.OutputTokens + b.OutputTokens,CachedInputTokens: a.CachedInputTokens + b.CachedInputTokens,+ CacheWriteInputTokens: a.CacheWriteInputTokens + b.CacheWriteInputTokens,ReasoningOutputTokens: a.ReasoningOutputTokens + b.ReasoningOutputTokens,}}diff --git a/server/pkg/agent/codex_interrupt_latency_integration_test.go b/server/pkg/agent/codex_interrupt_latency_integration_test.gonew file mode 100644index 0000000000..b3bc7df2e6--- /dev/null+++ b/server/pkg/agent/codex_interrupt_latency_integration_test.go@@ -0,0 +1,336 @@+//go:build agentintegration++package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "runtime"+ "sort"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"+)++const (+ codexInterruptSamplesEnv = "MULTICA_CODEX_INTERRUPT_SAMPLES"+ codexInterruptWarmupsEnv = "MULTICA_CODEX_INTERRUPT_WARMUPS"+ codexInterruptSettleDelayEnv = "MULTICA_CODEX_INTERRUPT_SETTLE_DELAY"+ codexInterruptModelEnv = "MULTICA_CODEX_INTERRUPT_MODEL"+)++type codexInterruptScenario struct {+ name string+ prompt string+ waitFor func(Message) bool+ waitForLog string+ settleDelay time.Duration+ sampleTimeout time.Duration+}++type codexInterruptSample struct {+ interruptLatency time.Duration+ resultLatency time.Duration+ status string+ inputTokens int64+ outputTokens int64+}++type synchronizedBuffer struct {+ mu sync.Mutex+ b bytes.Buffer+}++func (b *synchronizedBuffer) Write(p []byte) (int, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.b.Write(p)+}++func (b *synchronizedBuffer) String() string {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.b.String()+}++// TestCodexRealTurnInterruptLatency measures the real app-server boundary that+// TurnInterruptTimeout protects. It is intentionally excluded from ordinary+// test runs: besides requiring an installed, authenticated Codex CLI, every+// sample makes a provider request and may consume quota.+//+// Run it explicitly with:+//+// MULTICA_RUN_REAL_AGENT_SMOKE=1 go test -tags=agentintegration ./pkg/agent \+// -run TestCodexRealTurnInterruptLatency -count=1 -v+//+// MULTICA_CODEX_INTERRUPT_SAMPLES and MULTICA_CODEX_INTERRUPT_WARMUPS control+// the measured and discarded sample counts. MULTICA_CODEX_INTERRUPT_MODEL can+// pin a model; empty preserves the authenticated CLI's configured default.+// MULTICA_CODEX_INTERRUPT_SETTLE_DELAY controls how long generation continues+// after its first observed agent-message delta before cancellation.+func TestCodexRealTurnInterruptLatency(t *testing.T) {+ requireRealAgentSmoke(t)+ if testing.Short() {+ t.Skip("skipping real-binary interrupt latency test in -short mode")+ }+ path, err := exec.LookPath("codex")+ if err != nil {+ t.Skip("codex not on PATH; skipping real-binary interrupt latency test")+ }+ version := "unknown"+ if output, versionErr := exec.Command(path, "--version").CombinedOutput(); versionErr == nil {+ version = strings.TrimSpace(string(output))+ }++ samples := positiveEnvInt(t, codexInterruptSamplesEnv, 10, true)+ warmups := positiveEnvInt(t, codexInterruptWarmupsEnv, 1, false)+ settleDelay := durationEnv(t, codexInterruptSettleDelayEnv, 100*time.Millisecond)+ model := strings.TrimSpace(os.Getenv(codexInterruptModelEnv))++ t.Logf("environment: os=%s arch=%s codex=%q model=%q samples=%d warmups=%d settle_delay=%s",+ runtime.GOOS, runtime.GOARCH, version, model, samples, warmups, settleDelay)++ scenarios := []codexInterruptScenario{+ {+ name: "generation",+ prompt: "Write a detailed 2,000-word technical explanation of how cancellation propagates " ++ "through a concurrent server. Do not use tools. Start answering immediately and do not summarize.",+ waitForLog: `"activity":"item/agentMessage/delta:`,+ settleDelay: settleDelay,+ sampleTimeout: 90 * time.Second,+ },+ {+ name: "active_tool",+ prompt: "Use the shell tool now to run exactly `sleep 30`. After it exits, reply with exactly: done",+ waitFor: func(message Message) bool {+ return message.Type == MessageToolUse && message.Tool == "exec_command"+ },+ sampleTimeout: 90 * time.Second,+ },+ }++ for _, scenario := range scenarios {+ scenario := scenario+ t.Run(scenario.name, func(t *testing.T) {+ measured := make([]codexInterruptSample, 0, samples)+ for i := 0; i < warmups+samples; i++ {+ sample := runCodexInterruptSample(t, path, model, scenario)+ if i < warmups {+ t.Logf("warmup %d: interrupt=%s result=%s status=%s input_tokens=%d output_tokens=%d",+ i+1, sample.interruptLatency, sample.resultLatency, sample.status, sample.inputTokens, sample.outputTokens)+ continue+ }+ measured = append(measured, sample)+ t.Logf("sample %d/%d: interrupt=%s result=%s status=%s input_tokens=%d output_tokens=%d",+ i-warmups+1, samples, sample.interruptLatency, sample.resultLatency, sample.status, sample.inputTokens, sample.outputTokens)+ }++ interrupts := make([]time.Duration, 0, len(measured))+ results := make([]time.Duration, 0, len(measured))+ for _, sample := range measured {+ interrupts = append(interrupts, sample.interruptLatency)+ results = append(results, sample.resultLatency)+ }+ logCodexInterruptDistribution(t, "turn/interrupt_to_turn/completed", interrupts)+ logCodexInterruptDistribution(t, "cancel_to_session_result", results)+ })+ }+}++func runCodexInterruptSample(t *testing.T, path, model string, scenario codexInterruptScenario) codexInterruptSample {+ t.Helper()++ var logs synchronizedBuffer+ logger := slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))+ env := make(map[string]string)+ if codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME")); codexHome != "" {+ // The daemon passes its task-local CODEX_HOME explicitly. Mirror that+ // shape so the post-exit rollout fallback is exercised as well as the+ // live app-server notification path.+ env["CODEX_HOME"] = codexHome+ }+ backend := &codexBackend{cfg: Config{+ ExecutablePath: path,+ Env: env,+ Logger: logger,+ TaskID: "interrupt-latency-" + scenario.name,+ }}++ parentCtx, stop := context.WithTimeout(context.Background(), scenario.sampleTimeout)+ defer stop()+ runCtx, cancelRun := context.WithCancel(parentCtx)+ session, err := backend.executeOnce(runCtx, scenario.prompt, ExecOptions{+ Cwd: t.TempDir(),+ Model: model,+ Timeout: scenario.sampleTimeout,+ TurnInterruptTimeout: 10 * time.Second,+ ThinkingLevel: "low",+ }, 1)+ if err != nil {+ t.Fatalf("start Codex sample: %v", err)+ }++ cancelled := make(chan time.Time, 1)+ go func() {+ ticker := time.NewTicker(10 * time.Millisecond)+ defer ticker.Stop()+ for {+ triggered := false+ select {+ case message, ok := <-session.Messages:+ if !ok {+ return+ }+ triggered = scenario.waitFor != nil && scenario.waitFor(message)+ case <-ticker.C:+ triggered = scenario.waitForLog != "" && strings.Contains(logs.String(), scenario.waitForLog)+ case <-parentCtx.Done():+ return+ }+ if !triggered {+ continue+ }+ if scenario.settleDelay > 0 {+ timer := time.NewTimer(scenario.settleDelay)+ select {+ case <-timer.C:+ case <-parentCtx.Done():+ timer.Stop()+ return+ }+ }+ cancelAt := time.Now()+ cancelRun()+ cancelled <- cancelAt+ return+ }+ }()++ var cancelAt time.Time+ select {+ case cancelAt = <-cancelled:+ case result := <-session.Result:+ t.Fatalf("scenario %s ended before its cancellation trigger: status=%q error=%q\nlogs:\n%s",+ scenario.name, result.Status, result.Error, logs.String())+ case <-parentCtx.Done():+ t.Fatalf("scenario %s did not reach its cancellation trigger: %v\nlogs:\n%s", scenario.name, parentCtx.Err(), logs.String())+ }++ var result Result+ select {+ case result = <-session.Result:+ case <-parentCtx.Done():+ t.Fatalf("scenario %s did not return a result after cancellation: %v\nlogs:\n%s", scenario.name, parentCtx.Err(), logs.String())+ }+ resultLatency := time.Since(cancelAt)+ if result.Status != "aborted" {+ t.Fatalf("scenario %s status=%q error=%q, want aborted\nlogs:\n%s", scenario.name, result.Status, result.Error, logs.String())+ }+ var inputTokens, outputTokens int64+ for _, usage := range result.Usage {+ inputTokens += usage.InputTokens+ outputTokens += usage.OutputTokens+ }++ interruptLatency, err := codexInterruptLatencyFromLogs(logs.String())+ if err != nil {+ t.Fatalf("scenario %s: %v\nlogs:\n%s", scenario.name, err, logs.String())+ }+ return codexInterruptSample{+ interruptLatency: interruptLatency,+ resultLatency: resultLatency,+ status: result.Status,+ inputTokens: inputTokens,+ outputTokens: outputTokens,+ }+}++func codexInterruptLatencyFromLogs(logs string) (time.Duration, error) {+ for _, line := range strings.Split(logs, "\n") {+ if strings.TrimSpace(line) == "" {+ continue+ }+ var record map[string]any+ if err := json.Unmarshal([]byte(line), &record); err != nil {+ continue+ }+ if record["msg"] != "codex turn interrupted" {+ continue+ }+ latency, ok := record["latency"].(string)+ if !ok {+ return 0, fmt.Errorf("interrupt log has no string latency field")+ }+ parsed, err := time.ParseDuration(latency)+ if err != nil {+ return 0, fmt.Errorf("parse interrupt latency %q: %w", latency, err)+ }+ return parsed, nil+ }+ return 0, fmt.Errorf("no successful codex turn interrupt record found")+}++func logCodexInterruptDistribution(t *testing.T, label string, values []time.Duration) {+ t.Helper()+ if len(values) == 0 {+ t.Fatalf("no samples for %s", label)+ }+ sorted := append([]time.Duration(nil), values...)+ sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })+ t.Logf("SUMMARY %s n=%d p50=%s p95=%s p99=%s max=%s",+ label,+ len(sorted),+ nearestRankDuration(sorted, 0.50),+ nearestRankDuration(sorted, 0.95),+ nearestRankDuration(sorted, 0.99),+ sorted[len(sorted)-1],+ )+}++func nearestRankDuration(sorted []time.Duration, quantile float64) time.Duration {+ index := int(float64(len(sorted))*quantile+0.999999999) - 1+ if index < 0 {+ index = 0+ }+ if index >= len(sorted) {+ index = len(sorted) - 1+ }+ return sorted[index]+}++func positiveEnvInt(t *testing.T, name string, fallback int, requirePositive bool) int {+ t.Helper()+ raw := strings.TrimSpace(os.Getenv(name))+ if raw == "" {+ return fallback+ }+ value, err := strconv.Atoi(raw)+ if err != nil || value < 0 || (requirePositive && value == 0) {+ requirement := "a non-negative"+ if requirePositive {+ requirement = "a positive"+ }+ t.Fatalf("%s=%q must be %s integer", name, raw, requirement)+ }+ return value+}++func durationEnv(t *testing.T, name string, fallback time.Duration) time.Duration {+ t.Helper()+ raw := strings.TrimSpace(os.Getenv(name))+ if raw == "" {+ return fallback+ }+ value, err := time.ParseDuration(raw)+ if err != nil || value < 0 {+ t.Fatalf("%s=%q must be a non-negative Go duration", name, raw)+ }+ return value+}diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex c175fcb7f2..200fcb6fef 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -469,8 +469,8 @@ func TestCodexRawTurnStarted(t *testing.T) {if c.notificationProtocol != "raw" {t.Fatalf("expected protocol=raw, got %q", c.notificationProtocol)}- if c.turnID != "turn-1" {- t.Fatalf("expected turnID=turn-1, got %q", c.turnID)+ if turnID := c.activeTurnID(); turnID != "turn-1" {+ t.Fatalf("expected turnID=turn-1, got %q", turnID)}}@@ -1056,6 +1056,14 @@ func TestParseCodexSessionFileSinceResumeEdgeCases(t *testing.T) {},want: TokenUsage{InputTokens: 100, CacheReadTokens: 700},},+ {+ name: "cache write remains separate from plain input",+ lines: []string{+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1000,"cached_input_tokens":300,"cache_write_input_tokens":100}}}}`,+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1250,"cached_input_tokens":380,"cache_write_input_tokens":110}}}}`,+ },+ want: TokenUsage{InputTokens: 160, CacheReadTokens: 80, CacheWriteTokens: 10},+ },{name: "counter reset accumulates every segment",lines: []string{@@ -1566,8 +1574,8 @@ func TestCodexTurnNotificationGateIgnoresSubagentTurnStarted(t *testing.T) {if gate.turnID != "turn-main" {t.Fatalf("subagent turn/started replaced gate turnID: got %q", gate.turnID)}- if c.turnID != "turn-main" {- t.Fatalf("subagent turn/started replaced client turnID: got %q", c.turnID)+ if turnID := c.activeTurnID(); turnID != "turn-main" {+ t.Fatalf("subagent turn/started replaced client turnID: got %q", turnID)}if gotText != "Main answer" {t.Fatalf("main turn text was lost after subagent start: got %q", gotText)@@ -3681,6 +3689,370 @@ func TestCodexExecuteSurfacesUnsupportedServerRequestOnInterruptedTurn(t *testin}}+func TestCodexExecuteCancellationInterruptsTurnAndPreservesUsage(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ tempDir := t.TempDir()+ startedPath := filepath.Join(tempDir, "turn-started")+ interruptPath := filepath.Join(tempDir, "interrupt-request")+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-cancel-usage"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-cancel-usage","turn":{"id":"turn-cancel-usage"}}}'`+"\n"++ `echo started > `+startedPath+"\n"++ `read line`+"\n"++ `printf '%s\n' "$line" > `+interruptPath+"\n"++ `echo '{"jsonrpc":"2.0","id":4,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"thread/tokenUsage/updated","params":{"threadId":"thr-cancel-usage","turnId":"turn-cancel-usage","tokenUsage":{"total":{"inputTokens":100,"cachedInputTokens":30,"outputTokens":10,"reasoningOutputTokens":0,"totalTokens":110},"last":{"inputTokens":100,"cachedInputTokens":30,"outputTokens":10,"reasoningOutputTokens":0,"totalTokens":110},"modelContextWindow":200000}}}'`+"\n"++ // Real Codex v2 turn/completed has no usage field; accounting arrives in+ // the separate thread/tokenUsage/updated notification above.+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-cancel-usage","turn":{"id":"turn-cancel-usage","status":"interrupted"}}}'`+"\n")++ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new codex backend: %v", err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, err := backend.Execute(ctx, "prompt", ExecOptions{+ Model: "gpt-test",+ SemanticInactivityTimeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ deadline := time.Now().Add(5 * time.Second)+ for {+ if _, err := os.Stat(startedPath); err == nil {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("timeout waiting for fake Codex turn to start")+ }+ time.Sleep(10 * time.Millisecond)+ }+ cancel()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "aborted" {+ t.Fatalf("status = %q, want aborted (error=%q)", result.Status, result.Error)+ }+ usage, ok := result.Usage["gpt-test"]+ if !ok {+ t.Fatalf("cancelled turn usage missing: %+v", result.Usage)+ }+ if usage.InputTokens != 70 || usage.CacheReadTokens != 30 || usage.OutputTokens != 10 {+ t.Fatalf("cancelled turn usage = %+v, want input=70 cache_read=30 output=10", usage)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("timeout waiting for cancelled Codex result")+ }++ rawInterrupt, err := os.ReadFile(interruptPath)+ if err != nil {+ t.Fatalf("read interrupt request: %v", err)+ }+ var interruptRequest map[string]any+ if err := json.Unmarshal(rawInterrupt, &interruptRequest); err != nil {+ t.Fatalf("parse interrupt request: %v: %q", err, rawInterrupt)+ }+ if interruptRequest["method"] != "turn/interrupt" {+ t.Fatalf("method = %v, want turn/interrupt", interruptRequest["method"])+ }+ params, _ := interruptRequest["params"].(map[string]any)+ if params["threadId"] != "thr-cancel-usage" || params["turnId"] != "turn-cancel-usage" {+ t.Fatalf("interrupt params = %+v", params)+ }+}++func TestCodexThreadTokenUsageUpdatedDropsResumeReplay(t *testing.T) {+ c, _, _ := newTestCodexClient(t)+ c.notificationProtocol = "raw"+ c.threadID = "thread-resumed"+ gate := &codexTurnNotificationGate{}+ gate.arm()++ // Codex deliberately emits the restored historical usage after the+ // thread/resume response. The gate is armed by then, but no current turn ID+ // exists yet, so this prior-turn snapshot must not be charged.+ replay := codexThreadTokenUsageParams(+ "thread-resumed", "turn-previous",+ map[string]any{"inputTokens": float64(10_000), "outputTokens": float64(500)},+ map[string]any{"inputTokens": float64(400), "outputTokens": float64(20)},+ )+ if !gate.accept("thread/tokenUsage/updated", replay) {+ t.Fatal("armed notification gate should expose the resume replay to usage attribution")+ }+ c.handleRawNotification("thread/tokenUsage/updated", replay)+ c.handleRawNotification("turn/started", map[string]any{+ "threadId": "thread-resumed",+ "turn": map[string]any{"id": "turn-current"},+ })+ c.handleRawNotification("thread/tokenUsage/updated", codexThreadTokenUsageParams(+ "thread-resumed", "turn-current",+ map[string]any{"inputTokens": float64(10_100), "cachedInputTokens": float64(30), "outputTokens": float64(510)},+ map[string]any{"inputTokens": float64(100), "cachedInputTokens": float64(30), "outputTokens": float64(10)},+ ))++ c.usageMu.Lock()+ got := c.usage+ c.usageMu.Unlock()+ want := (TokenUsage{InputTokens: 70, OutputTokens: 10, CacheReadTokens: 30})+ if got != want {+ t.Fatalf("usage after resume replay = %+v, want current turn only %+v", got, want)+ }+}++func TestCodexThreadTokenUsageUpdatedDeduplicatesSnapshot(t *testing.T) {+ c := &codexClient{}+ c.setActiveTurnID("turn-current")+ params := codexThreadTokenUsageParams(+ "thread-1", "turn-current",+ map[string]any{"inputTokens": float64(10_100), "cachedInputTokens": float64(30), "outputTokens": float64(510)},+ map[string]any{"inputTokens": float64(100), "cachedInputTokens": float64(30), "outputTokens": float64(10)},+ )+ c.updateThreadTokenUsage(params)+ c.updateThreadTokenUsage(params)++ c.usageMu.Lock()+ got := c.usage+ c.usageMu.Unlock()+ want := (TokenUsage{InputTokens: 70, OutputTokens: 10, CacheReadTokens: 30})+ if got != want {+ t.Fatalf("usage after duplicate snapshot = %+v, want %+v", got, want)+ }+}++func TestCodexThreadTokenUsageUpdatedAccumulatesCurrentTurnResponses(t *testing.T) {+ c := &codexClient{}+ c.setActiveTurnID("turn-current")+ c.updateThreadTokenUsage(codexThreadTokenUsageParams(+ "thread-1", "turn-current",+ // The cumulative total includes resumed history and is deliberately much+ // larger than the first response being charged to this task.+ map[string]any{+ "inputTokens": float64(10_000), "cachedInputTokens": float64(2_000),+ "outputTokens": float64(100), "reasoningOutputTokens": float64(10),+ "cacheWriteInputTokens": float64(20),+ },+ map[string]any{+ "inputTokens": float64(100), "cachedInputTokens": float64(30),+ "outputTokens": float64(10), "reasoningOutputTokens": float64(2),+ "cacheWriteInputTokens": float64(4),+ },+ ))+ c.updateThreadTokenUsage(codexThreadTokenUsageParams(+ "thread-1", "turn-current",+ map[string]any{+ "inputTokens": float64(10_150), "cachedInputTokens": float64(2_050),+ "outputTokens": float64(120), "reasoningOutputTokens": float64(13),+ "cacheWriteInputTokens": float64(26),+ },+ map[string]any{+ "inputTokens": float64(150), "cachedInputTokens": float64(50),+ "outputTokens": float64(20), "reasoningOutputTokens": float64(3),+ "cacheWriteInputTokens": float64(6),+ },+ ))++ c.usageMu.Lock()+ got := c.usage+ c.usageMu.Unlock()+ want := (TokenUsage{InputTokens: 160, OutputTokens: 35, CacheReadTokens: 80, CacheWriteTokens: 10})+ if got != want {+ t.Fatalf("multi-response usage = %+v, want %+v", got, want)+ }+}++func codexThreadTokenUsageParams(threadID, turnID string, total, last map[string]any) map[string]any {+ return map[string]any{+ "threadId": threadID,+ "turnId": turnID,+ "tokenUsage": map[string]any{+ "total": total,+ "last": last,+ },+ }+}++func TestCodexCancellationDuringInitializeStopsProcessImmediately(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only; Windows ownership is covered in proc_windows_test.go")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(3 * time.Second))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ marker := filepath.Join(t.TempDir(), "initialize-read")+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo ready > `+marker+"\n"++ `sleep 30`+"\n")++ result, elapsed := cancelFakeCodexAfterMarker(t, fakePath, marker, ExecOptions{})+ if result.Status != "failed" || !strings.Contains(result.Error, "initialize failed") {+ t.Fatalf("unexpected result: %+v", result)+ }+ if elapsed > time.Second {+ t.Fatalf("initialize cancellation took %s; process cleanup should be immediate", elapsed)+ }+}++func TestCodexCancellationBeforeTurnStartedStopsProcessImmediately(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only; Windows ownership is covered in proc_windows_test.go")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(3 * time.Second))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ marker := filepath.Join(t.TempDir(), "turn-start-read")+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-race"}}}'`+"\n"++ `read line`+"\n"++ `echo ready > `+marker+"\n"++ `sleep 30`+"\n")++ result, elapsed := cancelFakeCodexAfterMarker(t, fakePath, marker, ExecOptions{})+ if result.Status != "aborted" {+ t.Fatalf("unexpected result: %+v", result)+ }+ if elapsed > time.Second {+ t.Fatalf("pre-turn/started cancellation took %s; process cleanup should be immediate", elapsed)+ }+}++func TestCodexNonResponsiveInterruptStopsProcessAtConfiguredDeadline(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only; Windows ownership is covered in proc_windows_test.go")+ }+ codexGracefulShutdownTimeoutNanos.Store(int64(3 * time.Second))+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })++ tempDir := t.TempDir()+ marker := filepath.Join(tempDir, "turn-started")+ interrupt := filepath.Join(tempDir, "interrupt-read")+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-stuck"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-stuck","turn":{"id":"turn-stuck"}}}'`+"\n"++ `echo ready > `+marker+"\n"++ `read line`+"\n"++ `echo interrupt > `+interrupt+"\n"++ `sleep 30`+"\n")++ result, elapsed := cancelFakeCodexAfterMarker(t, fakePath, marker, ExecOptions{TurnInterruptTimeout: 150 * time.Millisecond})+ if result.Status != "aborted" {+ t.Fatalf("unexpected result: %+v", result)+ }+ if _, err := os.Stat(interrupt); err != nil {+ t.Fatalf("turn/interrupt was not sent: %v", err)+ }+ if elapsed < 100*time.Millisecond || elapsed > time.Second {+ t.Fatalf("interrupt cleanup took %s; want configured wait followed by immediate process stop", elapsed)+ }+}++func TestCodexInterruptCompletesNearConfiguredDeadline(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ marker := filepath.Join(t.TempDir(), "turn-started")+ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-near-deadline"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-near-deadline","turn":{"id":"turn-near-deadline"}}}'`+"\n"++ `echo ready > `+marker+"\n"++ `read line`+"\n"++ `sleep 0.12`+"\n"++ `echo '{"jsonrpc":"2.0","id":4,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"thread/tokenUsage/updated","params":{"threadId":"thr-near-deadline","turnId":"turn-near-deadline","tokenUsage":{"total":{"inputTokens":12,"cachedInputTokens":2,"outputTokens":3,"reasoningOutputTokens":0,"totalTokens":15},"last":{"inputTokens":12,"cachedInputTokens":2,"outputTokens":3,"reasoningOutputTokens":0,"totalTokens":15},"modelContextWindow":200000}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-near-deadline","turn":{"id":"turn-near-deadline","status":"interrupted"}}}'`+"\n")++ result, elapsed := cancelFakeCodexAfterMarker(t, fakePath, marker, ExecOptions{+ Model: "gpt-test",+ TurnInterruptTimeout: 250 * time.Millisecond,+ })+ if result.Status != "aborted" {+ t.Fatalf("unexpected result: %+v", result)+ }+ if elapsed < 100*time.Millisecond || elapsed >= 250*time.Millisecond {+ t.Fatalf("interrupt completed in %s, want a near-deadline success below 250ms", elapsed)+ }+ if got := result.Usage["gpt-test"]; got.InputTokens != 10 || got.CacheReadTokens != 2 || got.OutputTokens != 3 {+ t.Fatalf("near-deadline usage = %+v", got)+ }+}++func cancelFakeCodexAfterMarker(t *testing.T, fakePath, marker string, opts ExecOptions) (Result, time.Duration) {+ t.Helper()+ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new codex backend: %v", err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ session, err := backend.Execute(ctx, "prompt", opts)+ if err != nil {+ cancel()+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ waitForCodexMarker(t, marker, 5*time.Second)+ started := time.Now()+ cancel()+ select {+ case result := <-session.Result:+ return result, time.Since(started)+ case <-time.After(5 * time.Second):+ t.Fatal("timeout waiting for cancelled Codex result")+ return Result{}, 0+ }+}++func waitForCodexMarker(t *testing.T, path string, within time.Duration) {+ t.Helper()+ deadline := time.Now().Add(within)+ for time.Now().Before(deadline) {+ if _, err := os.Stat(path); err == nil {+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", path)+}+func TestCodexExecuteTimeoutWinsOverProcessExitDuringActiveTurn(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {diff --git a/server/pkg/agent/proc_windows_test.go b/server/pkg/agent/proc_windows_test.goindex bb938d1cab..c266198583 100644--- a/server/pkg/agent/proc_windows_test.go+++ b/server/pkg/agent/proc_windows_test.go@@ -437,6 +437,108 @@ func main() {}}+func TestCodexWindowsCancelledTurnKillsOwnedDescendantsWhenInterruptStalls(t *testing.T) {+ tempDir := t.TempDir()+ sourcePath := filepath.Join(tempDir, "fake_codex_cancel.go")+ exePath := filepath.Join(tempDir, "fake_codex_cancel.exe")+ pidPath := filepath.Join(tempDir, "descendant.pid")+ startedPath := filepath.Join(tempDir, "turn-started")+ const source = `package main+import (+ "bufio"+ "fmt"+ "os"+ "os/exec"+ "time"+)+func main() {+ if len(os.Args) > 1 && os.Args[1] == "--version" { fmt.Println("codex-cli windows-test"); return }+ if len(os.Args) > 1 && os.Args[1] == "descendant" { time.Sleep(30*time.Second); return }+ s := bufio.NewScanner(os.Stdin)+ if !s.Scan() { return }+ fmt.Println("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}")+ if !s.Scan() { return }+ if !s.Scan() { return }+ fmt.Println("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"thread\":{\"id\":\"thr-windows-cancel\"}}}")+ if !s.Scan() { return }+ fmt.Println("{\"jsonrpc\":\"2.0\",\"id\":3,\"result\":{}}")+ fmt.Println("{\"jsonrpc\":\"2.0\",\"method\":\"turn/started\",\"params\":{\"threadId\":\"thr-windows-cancel\",\"turn\":{\"id\":\"turn-windows-cancel\"}}}")+ child := exec.Command(os.Args[0], "descendant")+ child.Stdout = os.Stdout+ child.Stderr = os.Stderr+ if err := child.Start(); err != nil { panic(err) }+ _ = os.WriteFile(os.Getenv("DESCENDANT_PID_FILE"), []byte(fmt.Sprint(child.Process.Pid)), 0600)+ _ = os.WriteFile(os.Getenv("TURN_STARTED_FILE"), []byte("ready"), 0600)+ if !s.Scan() { return }+ time.Sleep(time.Hour)+}`+ if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil {+ t.Fatal(err)+ }+ build := exec.Command("go", "build", "-o", exePath, sourcePath)+ if output, err := build.CombinedOutput(); err != nil {+ t.Fatalf("build Windows fake app-server: %v: %s", err, output)+ }++ codexGracefulShutdownTimeoutNanos.Store(int64(2 * time.Second))+ codexProcessWaitDelayNanos.Store(int64(200 * time.Millisecond))+ t.Cleanup(func() {+ codexGracefulShutdownTimeoutNanos.Store(0)+ codexProcessWaitDelayNanos.Store(0)+ })++ backend, err := New("codex", Config{+ ExecutablePath: exePath,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ Env: map[string]string{+ "DESCENDANT_PID_FILE": pidPath,+ "TURN_STARTED_FILE": startedPath,+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ session, err := backend.Execute(ctx, "prompt", ExecOptions{+ Timeout: 5 * time.Second,+ HandshakeTimeout: time.Second,+ TurnInterruptTimeout: 100 * time.Millisecond,+ })+ if err != nil {+ t.Fatal(err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ waitForWindowsPath(t, startedPath, 10*time.Second)+ descendantPid := waitForDescendantPid(t, pidPath)+ started := time.Now()+ cancel()+ result := <-session.Result+ if elapsed := time.Since(started); elapsed > 3*time.Second {+ t.Fatalf("cancel cleanup exceeded bound: %s", elapsed)+ }+ if result.Status != "aborted" {+ t.Fatalf("expected aborted, got %+v", result)+ }+ if processStillRunning(descendantPid) {+ t.Fatalf("descendant %d survived stalled interrupt cleanup", descendantPid)+ }+}++func waitForWindowsPath(t *testing.T, path string, within time.Duration) {+ t.Helper()+ deadline := time.Now().Add(within)+ for time.Now().Before(deadline) {+ if _, err := os.Stat(path); err == nil {+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", path)+}+func phaseCount(entries []map[string]any, phase string) int {count := 0for _, entry := range entries {