Repository navigation
AIエージェントの応答をSSEストリーミングで逐次表示するよう対応 - #6492
Conversation
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017RfgmFqn92SHMdeRPUXgEP
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017RfgmFqn92SHMdeRPUXgEP
📝 WalkthroughWalkthroughAIエージェント通信をJSON応答からSSEストリーミングへ変更しました。SSEパーサー、通信フック、逐次表示画面、エラー処理、仕様書、テストを更新しました。 ChangesAIエージェントのSSEストリーミング
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant DestinationAgent
participant useDestinationAgent
participant SSEParser
participant AgentStreamEndpoint
DestinationAgent->>useDestinationAgent: sendMessages(messages, handlers)
useDestinationAgent->>AgentStreamEndpoint: POST /agent/chat/stream
AgentStreamEndpoint-->>useDestinationAgent: delta/tool/done/error
useDestinationAgent->>SSEParser: parse Uint8Array chunks
SSEParser-->>useDestinationAgent: parsed SSE events
useDestinationAgent-->>DestinationAgent: onDelta or final result
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/hooks/useDestinationAgent.test.ts (1)
356-386: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winフェイクタイマーの解除を
afterEachに移してください。現在は
jest.useRealTimers()をテスト本体の末尾で呼びます。途中のアサーションが失敗すると、この行は実行されません。フェイクタイマーが後続テストへ残り、無関係なテストが失敗します。既存のafterEachで解除すれば、失敗時も状態が戻ります。♻️ 提案する変更
afterEach(() => { jest.clearAllMocks(); + jest.useRealTimers(); });await expect(promise).resolves.toEqual({ ok: false, error: 'timeout' }); - - jest.useRealTimers(); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/hooks/useDestinationAgent.test.ts` around lines 356 - 386, テスト本体末尾のjest.useRealTimers()を削除し、既存のafterEachへフェイクタイマー解除処理を移してください。タイムアウトテストでアサーションが失敗した場合も、各テスト後に必ず実タイマーへ復元されるようにしてください。docs/spec/ai-agent/architecture.md (1)
841-853: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win画面ファイルのパス表記を文書内で統一してください。
この表は
src/screens/DestinationAgent/index.tsxを記載しています。実装もこのパスです。一方、上の「変更ファイル一覧(想定)」はsrc/screens/DestinationAgentScreen.tsxと記載しています。同一文書内でパスが二通りになり、読み手が実体を追えません。既存表側の表記を実際のディレクトリ構成に合わせて更新してください。コーディングガイドラインの「ensure documentation matches the current directory structure and script names, update cross-references」に基づく指摘です。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/spec/ai-agent/architecture.md` around lines 841 - 853, 文書内の画面ファイルパス表記を実際の構成に統一してください。変更ファイル一覧(想定)の DestinationAgentScreen.tsx 表記を、ストリーミング対応表および実装で使用している src/screens/DestinationAgent/index.tsx に更新し、他の参照も同じパスへ揃えてください。Source: Coding guidelines
src/screens/DestinationAgent/index.tsx (1)
197-208: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value追従スクロールのアンカーに提案カードの解決状態も含める検討をしてください。
scrollAnchorは末尾エントリの本文長だけを見ます。doneの後にresolveSuggestionsが完了して提案カードが描画されると、コンテンツの高さは伸びますが本文長は変わりません。このためスクロールは発火せず、提案カードが画面外に残る場合があります。ユーザは手動スクロールで到達できるため軽微です。なお
scrollAnchor.startsWith('0:')は「エントリが空」の判定を文字列の前方一致で表現しています。entries.length === 0を直接使うと意図が明確になります。♻️ 提案する変更
- const scrollAnchor = `${entries.length}:${ - entries[entries.length - 1]?.content.length ?? 0 - }`; + const lastEntry = entries[entries.length - 1]; + // 追従スクロールの発火キー。本文の伸びと、提案カードの解決による + // 高さ変化の両方でキーを変える + const scrollAnchor = `${entries.length}:${lastEntry?.content.length ?? 0}:${ + lastEntry ? (suggestionStates[lastEntry.id]?.status ?? 'none') : 'none' + }`; useEffect(() => { - if (scrollAnchor.startsWith('0:')) { + if (entries.length === 0) { return; } scrollRef.current?.scrollToEnd({ animated: true }); - }, [scrollAnchor]); + }, [scrollAnchor, entries.length]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/screens/DestinationAgent/index.tsx` around lines 197 - 208, Update scrollAnchor in the component containing the scroll-follow effect to include the trailing entry’s suggestion-resolution state, such as its resolved suggestion data or equivalent existing state, so the effect reruns when suggestion cards render after resolveSuggestions completes. Replace the scrollAnchor.startsWith('0:') check with a direct entries.length === 0 condition while preserving the existing scrollToEnd behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@docs/spec/ai-agent/architecture.md`:
- Around line 841-853: 文書内の画面ファイルパス表記を実際の構成に統一してください。変更ファイル一覧(想定)の
DestinationAgentScreen.tsx 表記を、ストリーミング対応表および実装で使用している
src/screens/DestinationAgent/index.tsx に更新し、他の参照も同じパスへ揃えてください。
In `@src/hooks/useDestinationAgent.test.ts`:
- Around line 356-386:
テスト本体末尾のjest.useRealTimers()を削除し、既存のafterEachへフェイクタイマー解除処理を移してください。タイムアウトテストでアサーションが失敗した場合も、各テスト後に必ず実タイマーへ復元されるようにしてください。
In `@src/screens/DestinationAgent/index.tsx`:
- Around line 197-208: Update scrollAnchor in the component containing the
scroll-follow effect to include the trailing entry’s suggestion-resolution
state, such as its resolved suggestion data or equivalent existing state, so the
effect reruns when suggestion cards render after resolveSuggestions completes.
Replace the scrollAnchor.startsWith('0:') check with a direct entries.length ===
0 condition while preserving the existing scrollToEnd behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f9c5068a-f28e-47bd-bcb7-6c4c5b303e2a
📒 Files selected for processing (6)
docs/spec/ai-agent/architecture.mdsrc/hooks/useDestinationAgent.test.tssrc/hooks/useDestinationAgent.tssrc/screens/DestinationAgent/index.tsxsrc/utils/sse.test.tssrc/utils/sse.ts
概要
AI エージェント(行き先相談チャット)の応答を SSE によるストリーミングで逐次表示するよう対応しました。従来は tool use ループを含む確定応答(最大 20 秒程度)をローディング表示だけで待たせていましたが、
POST /agent/chat/streamからreply本文の増分(delta)を受信して随時描画します。設計書docs/spec/ai-agent/architecture.mdの「ストリーミング」節(従来スコープ外 → 今回スコープ内へ昇格)を先に更新し、その設計に沿って実装しています。BFF 側のエンドポイント実装(
streamText化 + SSE 配信)は TrainLCD/BFF リポジトリ側で別途 PR を作成します。変更の種類
変更内容
docs/spec/ai-agent/architecture.md: ストリーミング節を SSE 配信設計へ全面更新(エンドポイント仕様・イベント仕様delta/tool/done/error・サーバ / クライアント実装方針・タイムアウト・エラーハンドリング・変更ファイル一覧・未決事項 4 の決定化)src/utils/sse.ts(新規): 依存ゼロの最小 SSE パーサ。純関数parseSSEChunk(複数行dataの連結・コメント行無視・CRLF・チャンク跨ぎのバッファリング)と、TextDecoder(stream: true)を内包した逐次パーサcreateSSEParsersrc/hooks/useDestinationAgent.ts:expo/fetchで/agent/chat/streamに POST しres.bodyを逐次読取。sendMessages(messages, handlers?)に拡張(onDelta/onToolStart)。戻り値の形とエラー種別(rateLimited/timeout/network)は現行維持。expo/fetchは中断時に DOM 準拠のAbortErrorを投げないため、30 秒タイムアウトは自前フラグで判定src/screens/DestinationAgent/index.tsx: 送信開始時に仮置きの assistant バブルを追加しdeltaで本文を追記、doneの確定値で置き換えてから提案カード解決と読み上げを実行。エラー時は仮置きと未応答のユーザ発話を除去。会話リセット世代ガードとストリーミング中の追従スクロールに対応src/utils/sse.test.ts(新規)・src/hooks/useDestinationAgent.test.ts: SSE パーサ 14 件・フック 22 件(expo/fetchをReadableStreamでモックし、チャンク分割・マルチバイト境界・中断系を検証)テスト
npm run lintが通ることnpm testが通ることnpm run typecheckが通ることnpm testは全体で 198 suites / 2138 tests パス。dev ビルドでのストリーミング表示の手動 QA(BFF 側デプロイ後の結合確認)は未実施です。関連Issue
スクリーンショット(任意)
Summary by CodeRabbit