Skip to content

fix(desktop): Codex 重さ調査ログ改善・xterm rAFバッファ・JSONL タイムアウト延長 (#293)#381

Merged
MocA-Love merged 4 commits intomainfrom
fix/codex-performance-investigation
Apr 21, 2026
Merged

fix(desktop): Codex 重さ調査ログ改善・xterm rAFバッファ・JSONL タイムアウト延長 (#293)#381
MocA-Love merged 4 commits intomainfrom
fix/codex-performance-investigation

Conversation

@MocA-Love
Copy link
Copy Markdown
Owner

@MocA-Love MocA-Love commented Apr 21, 2026

概要

Issue #293「Codexが重い」の Sentry ログ調査(PR #341/#344)で得られた知見をもとに修正。


変更一覧

# ファイル 変更内容 デメリット
1 shared/debug-channel.ts Sentry 集計間隔を 1秒 → 30秒 に延長 Sentry ログの時系列粒度が粗くなる。調査中は解像度が下がるトレードオフ
2 v1-terminal-cache.ts rAF write バッファを追加。scheduleWrite で1フレーム分のデータを束ねて1回の xterm.write に集約 PTY出力の描画が最大16ms(1フレーム)遅延する。人間には知覚不可だが原理上の遅延は存在する
3 v1-terminal-cache.ts flushWrite をエクスポート。exit/disconnect/error イベント処理前と hidden経路のキュー前に呼び出し、trailing output の消失を防止 なし
4 v1-terminal-cache.ts HMR 復元ブロックで rafWriteBuffer ??= "" / rafWriteId ??= null を追加。ホットリロード後のフィールド欠落バグを修正 なし(開発時のみの修正)
5 useTerminalStream.ts マウント時の xterm.writescheduleWrite 経由に変更(#2 の適用) #2 と同じ(最大16ms遅延)
6 terminal-cleanup.ts killTerminalForPane から dispose を除去し、releaseTerminalCache を独立した関数として追加 なし
7 store.ts ペイン削除後(delete newPanes[id] の直後)に releaseTerminalCache を呼び、xterm/WebGL リソースを確実に解放 なし(dispose は idempotent)
8 pty-turn-runner.ts JSONL 発見タイムアウトを 15秒 → 30秒 に延長 Todo Agent の失敗検出が最大15秒遅くなる
8 pty-turn-runner.ts タイムアウト時のエラーメッセージに projectDir の実在ファイル一覧を追記 なし(ローカル完結、外部送信なし)

根本原因の整理

Sentry 9エージェント並列調査から判明した原因と対応関係:

原因 深刻度 本PRでの対応
Sentry 集計ログが毎秒送信され、調査ログ自体が CPU/メモリ負荷を生んでいた #1 で解消
xterm.write がスロットリングなしで毎秒30回呼ばれ、描画負荷が高かった 中〜大 #2 #5 で緩和
hidden keepalive は意図的設計(リークではない) 対処不要
mount/unmount 非対称によるリソース残留リスク #6 #7 で解消
Todo Agent が JSONL 生成タイミング差で15秒タイムアウトに引っかかっていた #8 で解消

残課題

  • allowTransparency: true の WebGL 描画コスト(視覚確認後に判断)
  • scrollback 5000行のGPUメモリ消費(ユーザー設定化 or デフォルト削減を別途検討)
  • Codex TUI 自体の CPU 負荷(rAF バッファの効果を次回 Sentry ログで確認予定)

Closes 一部 #293(根本的な Codex TUI 負荷自体は継続調査)

Sentry ログ調査(PR #341/#344)で得られた知見をもとに修正。

- debug-channel: 集計間隔を 1 秒 → 30 秒に延長
  毎秒 Sentry にイベントが飛び続けていた問題を解消。
  これ自体が CPU/メモリの追加負荷になっていた可能性がある。

- v1-terminal-cache: rAF ベースの write バッファを追加
  xterm.write を 1 フレーム(16ms)単位でまとめて呼ぶようにし、
  パーサ/レンダリングサイクルの回数を削減。
  hidden 経路・マウント時経路の両方に適用。

- terminal-cleanup: killTerminalForPane に v1TerminalCache.dispose を追加
  React unmount が遅延した場合でも xterm.js / WebGL リソースを
  ペイン削除時点で確実に解放する。

- pty-turn-runner: JSONL 発見タイムアウトを 15 秒 → 30 秒に延長
  Claude Code の JSONL 生成が SessionStart hook 発火より遅れる場合に
  15 秒以内で失敗していた問題を修正。
  タイムアウト時のエラーメッセージに実在ファイル一覧を追記。
@chatgpt-codex-connector
Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@MocA-Love
Copy link
Copy Markdown
Owner Author

@codex review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 21, 2026

📝 Walkthrough

Walkthrough

このPRはターミナルデータ処理を最適化し、エラー診断機能を強化します。リクエストアニメーションフレームベースのバッチ処理によるターミナル書き込み、タイムアウト・集約間隔の延長、ディレクトリ列挙による詳細エラーメッセージ、ターミナル破棄時の初期化ロジックが複数ファイルで実装されます。

Changes

Cohort / File(s) Summary
ターミナル書き込み最適化
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalStream.ts, apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache.ts
ターミナルデータの直接書き込みから、rAFベースのバッチ処理を使用したscheduleWrite()への切り替え。キャッシュされたターミナルにrafWriteBufferrafWriteIdを追加し、単一フレームで複数の書き込みを集約。
ターミナルライフサイクル管理
apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts
killTerminalForPane()において、リモートmutation前にv1TerminalCacheの即座な破棄を実行。xterm/WebGLリソースの早期解放。
診断とタイミング調整
apps/desktop/src/main/todo-daemon/pty-turn-runner.ts, apps/desktop/src/shared/debug-channel.ts
JSONLファイル発見タイムアウトを15秒から30秒に延長し、エラーパスで既存.jsonlファイルの列挙を追加。デバッグチャネルの既定集約間隔を1秒から30秒に延長。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 ふわり、ふわりと羽ばたいて
バッチ処理の時間巻き戻し
フレーム待つデータたち
さくさくと、整然と並ぶ
ターミナルの流れ、スムーズに...✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning PR説明は詳細な日本語で提供されていますが、指定されたテンプレートの要件を満たしていません。 英語での説明セクションを追加し、Related Issues、Type of Change、Testing、Screenshots(該当時)の各セクションを補完してください。テンプレート形式に合わせて構造化してください。
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは主要な4点の修正(Sentryログ改善、xterm rAFバッファ、JSONL タイムアウト延長)を簡潔に表現しており、変更内容の核心を正確に反映しています。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/codex-performance-investigation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d9d07460dd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts (1)

3-3: 追加importはaliasに寄せてください。

この深い相対パスは移動に弱いので、既存の renderer/... aliasで参照する方が安全です。

修正例
-import * as v1TerminalCache from "../../../screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache";
+import * as v1TerminalCache from "renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache";

As per coding guidelines, apps/desktop/**/*.{ts,tsx} should "Use aliases as defined in tsconfig.json when possible".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts` at line 3,
この行で使っている深い相対パスをプロジェクトの tsconfig エイリアスに合わせて置き換えてください: import * as
v1TerminalCache from
"../../../screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache";
— 対象モジュール識別子は v1TerminalCache なので、同じモジュールを指すエイリアス版(例: renderer/screens/...
などプロジェクトで定義されているパス)に差し替えて、相対パスへの依存をなくしてください。
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/main/todo-daemon/pty-turn-runner.ts`:
- Around line 333-345: The current error builds foundStr by joining foundJsonls
and injects raw filenames into the returned error (see foundJsonls, foundStr and
the returned error object), which can expose other session IDs; change it to
avoid leaking full filenames by replacing the joined filename list with either a
count-only message (e.g. "projectDir に .jsonl が N 件見つかりました") or a masked sample
(e.g. show up to 2 filenames with their middle characters redacted like
"ab****yz.jsonl"); update the construction of foundStr and the error strings to
use the sanitized count/masked sample instead of the unmasked foundJsonls values
so the returned error never contains full session identifiers.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache.ts`:
- Around line 57-59: When HMR restores an older CachedTerminal instance it may
lack the new rAF fields causing rafWriteBuffer to become "undefined..." or
rafWriteId checks to fail; update CachedTerminal initialization (e.g.,
constructor or any restore/revive path) to explicitly backfill rafWriteBuffer =
"" and rafWriteId = null, and ensure scheduleWrite uses these initialized fields
safely (referencing rafWriteBuffer, rafWriteId, scheduleWrite, and
CachedTerminal); apply the same backfill for the other restored instances where
rafWriteBuffer/rafWriteId were added (the corresponding CachedTerminal
restoration code paths).
- Around line 227-242: The delayed write via scheduleWrite can be lost if
lifecycle events (exit/error/disconnect) are handled in the same frame; add a
synchronous flush path that drains rafWriteBuffer to xterm before processing
non-data lifecycle events. Implement a helper (e.g., flushPendingWrite(paneId))
that looks up the cache entry, if rafWriteId exists
cancelAnimationFrame(rafWriteId), if rafWriteBuffer is non-empty call
e.xterm.write(e.rafWriteBuffer) and then clear rafWriteBuffer and set rafWriteId
to null; call this helper from the lifecycle handlers that process
exit/error/disconnect (and the code paths referenced around lines 257-278)
before queuing/removing the pane or logging the lifecycle event.

---

Nitpick comments:
In `@apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts`:
- Line 3: この行で使っている深い相対パスをプロジェクトの tsconfig エイリアスに合わせて置き換えてください: import * as
v1TerminalCache from
"../../../screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache";
— 対象モジュール識別子は v1TerminalCache なので、同じモジュールを指すエイリアス版(例: renderer/screens/...
などプロジェクトで定義されているパス)に差し替えて、相対パスへの依存をなくしてください。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c3571002-7ca3-4ad9-bde7-fee177f6ee8a

📥 Commits

Reviewing files that changed from the base of the PR and between 38a022e and d9d0746.

📒 Files selected for processing (5)
  • apps/desktop/src/main/todo-daemon/pty-turn-runner.ts
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalStream.ts
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/v1-terminal-cache.ts
  • apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts
  • apps/desktop/src/shared/debug-channel.ts

Comment thread apps/desktop/src/main/todo-daemon/pty-turn-runner.ts
- useTerminalStream: exit/disconnect/error イベント処理前に flushWrite を呼び、
  trailing output が exitバナーより先に描画されるバグを修正 (Codex レビュー指摘)
- v1-terminal-cache: flushWrite をエクスポート
- terminal-cleanup: killTerminalForPane から dispose を除去し、
  releaseTerminalCache を別関数として追加
- store: paneをstateから削除した直後に releaseTerminalCache を呼ぶよう変更
  (React unmount と同バッチになるため、dispose前にコンポーネントが動くリスクを排除)
- HMR復元時に rafWriteBuffer/rafWriteId を ??= で初期化し、
  旧モジュールから引き継いだエントリで undefined になるバグを修正
- routeEvent の hidden 経路で非dataイベントをキューに入れる前に
  flushWrite を呼び、data→exit の順序が保たれるよう修正
@MocA-Love
Copy link
Copy Markdown
Owner Author

@codex review

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: df0a5fa198

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant