Skip to content

AIエージェントの応答をSSEストリーミングで逐次表示するよう対応 - #6492

Merged
TinyKitten merged 2 commits into
devfrom
feature/ai-agent-streaming
Jul 31, 2026
Merged

TinyKitten merged 2 commits into
devfrom
feature/ai-agent-streaming

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

概要

AI エージェント(行き先相談チャット)の応答を SSE によるストリーミングで逐次表示するよう対応しました。従来は tool use ループを含む確定応答(最大 20 秒程度)をローディング表示だけで待たせていましたが、POST /agent/chat/stream から reply 本文の増分(delta)を受信して随時描画します。設計書 docs/spec/ai-agent/architecture.md の「ストリーミング」節(従来スコープ外 → 今回スコープ内へ昇格)を先に更新し、その設計に沿って実装しています。

BFF 側のエンドポイント実装(streamText 化 + SSE 配信)は TrainLCD/BFF リポジトリ側で別途 PR を作成します。

変更の種類

  • バグ修正
  • 新機能
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

  • docs/spec/ai-agent/architecture.md: ストリーミング節を SSE 配信設計へ全面更新(エンドポイント仕様・イベント仕様 delta / tool / done / error・サーバ / クライアント実装方針・タイムアウト・エラーハンドリング・変更ファイル一覧・未決事項 4 の決定化)
  • src/utils/sse.ts(新規): 依存ゼロの最小 SSE パーサ。純関数 parseSSEChunk(複数行 data の連結・コメント行無視・CRLF・チャンク跨ぎのバッファリング)と、TextDecoder(stream: true) を内包した逐次パーサ createSSEParser
  • src/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

  • 新機能
    • AIエージェントがストリーミング応答に対応しました。
    • 生成中の文章を逐次表示し、ツール実行の開始状態も表示します。
    • 応答完了時に最終メッセージへ自動更新します。
  • 改善
    • タイムアウト、通信エラー、レート制限などを適切に処理します。
    • 会話リセット後の遅延応答を破棄し、表示の不整合を防止します。
  • ドキュメント
    • ストリーミングAPI、イベント仕様、エラー処理、テスト方針を追加しました。

@TinyKitten TinyKitten self-assigned this Jul 31, 2026
@github-actions github-actions Bot added the react label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

AIエージェント通信をJSON応答からSSEストリーミングへ変更しました。SSEパーサー、通信フック、逐次表示画面、エラー処理、仕様書、テストを更新しました。

Changes

AIエージェントのSSEストリーミング

Layer / File(s) Summary
SSE仕様とパーサー
docs/spec/ai-agent/architecture.md, src/utils/sse.ts, src/utils/sse.test.ts
POST /agent/chat/stream と delta・tool・done・errorイベントの仕様を追加しました。チャンク分割、CRLF、複数行データ、マルチバイト文字に対応するSSEパーサーとテストを追加しました。
ストリーミング通信フック
src/hooks/useDestinationAgent.ts, src/hooks/useDestinationAgent.test.ts
useDestinationAgent がSSEを逐次読み取り、増分本文、ツール開始、確定結果を処理します。タイムアウト、HTTPエラー、ストリーム中断、不正なイベント、reader解放をテストします。
ストリーミング画面表示
src/screens/DestinationAgent/index.tsx
送信時に仮アシスタントエントリを追加し、deltaを逐次表示します。完了時に確定結果へ置換し、失敗時に仮エントリを削除します。

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
Loading

Possibly related PRs

Poem

うさぎがSSEをぴょんと受信、
deltaを重ねて返事を更新。
doneで答えをきれいに確定、
errorなら履歴を安全に整理。
にんじん色のストリーム万歳!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは、AIエージェントの応答をSSEストリーミングで逐次表示する主要変更を明確に示しています。
Description check ✅ Passed 概要、変更内容、テスト結果、変更種別を記載し、任意項目を除くテンプレートの必須情報を満たしています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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 feature/ai-agent-streaming

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between dbeaf43 and f06cde9.

📒 Files selected for processing (6)
  • docs/spec/ai-agent/architecture.md
  • src/hooks/useDestinationAgent.test.ts
  • src/hooks/useDestinationAgent.ts
  • src/screens/DestinationAgent/index.tsx
  • src/utils/sse.test.ts
  • src/utils/sse.ts

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant