Skip to content

iOSでAIエージェントのSSEが受信できない問題をXHR受信と非ストリーミングフォールバックで修正 - #6494

Merged
TinyKitten merged 3 commits into
devfrom
fix/ios-agent-streaming
Jul 31, 2026
Merged

TinyKitten merged 3 commits into
devfrom
fix/ios-agent-streaming

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

概要

EAS ビルドの iOS 実機で AI エージェントチャットが毎回「リクエストを正常に処理できませんでした」エラーになる問題の修正。原因は expo/fetch の iOS ネイティブ実装の既知不具合(expo/expo#42161 のチャンク欠落・順序逆転の競合)で、SSE の done イベントが JS に届かないままストリームが閉じるため。サーバ側(/agent/chat/stream)は正常に完走していることを wrangler tail で確認済み。

変更の種類

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

変更内容

  • iOS の SSE 受信を expo/fetch から XMLHttpRequest の逐次テキスト受信(sendViaXhrStream)に切替。send() 前に onreadystatechange / onprogress を登録して RN の逐次配送を有効化し、responseText の未処理分を既存の parseSSEChunk で解釈する。Android / web は従来どおり expo/fetch
  • 全プラットフォーム共通で、ストリーミングが network 系の失敗に終わった場合のみ非ストリーミングの POST /agent/chat(標準 fetch + JSON)へ 1 回フォールバックする sendViaJson を追加(rateLimited / timeout はフォールバックしない)
  • patches/expo+55.0.26.patch を追加(patch-package)。expo/fetch の FetchResponse が reader.cancel() 後の didComplete / didFailWithError で二重クローズし TypeError: The stream is not in a state that permits close を投げる競合([expo] fix expo/fetch fatal close race after stream cancel expo/expo#44909。Android 実機リリースビルドの logcat で観測)へのガード
  • 設計書(docs/spec/ai-agent/architecture.md)に iOS の XHR 経路・フォールバック方針・expo パッチを反映
  • useDestinationAgent のテストを拡張(XHR フェイクでの逐次配送・チャンク境界跨ぎ・429・フォールバック成否・タイムアウト等、計 37 件)

公開 API(sendMessages / AgentStreamHandlers / AgentErrorKind)は不変で、画面側は無改修。

テスト

Android 実機(assembleDevRelease のリリースビルド)でストリーミングの逐次表示を回帰確認済み。iOS は TestFlight(EAS ビルド)で検証予定。

  • npm run lint が通ること
  • npm test が通ること
  • npm run typecheck が通ること

関連Issue

スクリーンショット(任意)

Summary by CodeRabbit

  • 改善

    • ストリーミング中のネットワーク障害時に、非ストリーミング通信へ1回だけ自動で切り替えるようになりました。
    • Android・Web・iOSで、それぞれの環境に適したストリーミング方式を利用します。
    • SSEメッセージやツールイベントの受信処理を改善しました。
    • レート制限や認証エラーなど、再試行すべきでないエラーを適切に扱うようになりました。
  • バグ修正

    • 通信終了時の重複処理を防ぎ、ストリーミングの安定性を向上しました。

@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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ad2e0237-2b97-4aad-b594-1a7f8cfd1ce3

📥 Commits

Reviewing files that changed from the base of the PR and between 7422727 and 3ff09cb.

📒 Files selected for processing (3)
  • docs/spec/ai-agent/architecture.md
  • src/hooks/useDestinationAgent.test.ts
  • src/hooks/useDestinationAgent.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/hooks/useDestinationAgent.test.ts
  • docs/spec/ai-agent/architecture.md
  • src/hooks/useDestinationAgent.ts

📝 Walkthrough

Walkthrough

useDestinationAgent はプラットフォーム別のSSEストリーミングを使い、network エラー時だけ非ストリーミングAPIへ1回フォールバックする。iOS向けXHR処理、Android/web向けexpo/fetch処理、重複クローズ防止パッチ、関連テストと仕様を追加した。

Changes

AIエージェント通信

Layer / File(s) Summary
プラットフォーム別ストリーミング
src/hooks/useDestinationAgent.ts, src/hooks/useDestinationAgent.test.ts, docs/spec/ai-agent/architecture.md
共通リクエストと結果変換を追加した。Android/webではexpo/fetchのReadableStreamを使い、iOSではXHRの進捗通知からSSEを解析する。SSEイベント、HTTPエラー、タイムアウト、途中切断を検証する。
ネットワークエラー時のJSONフォールバック
src/hooks/useDestinationAgent.ts, src/hooks/useDestinationAgent.test.ts, docs/spec/ai-agent/architecture.md
ストリーミング結果がnetworkの場合だけ、同じ本文で非ストリーミングJSON POSTを1回実行する。429、タイムアウト、フォールバック失敗、イベント抑制を検証する。
ストリーム終了保護と仕様更新
patches/expo+55.0.26.patch, docs/spec/ai-agent/architecture.md
FetchResponseの完了・失敗イベントで終了済み状態を確認し、コントローラーの重複終了を防止する。設計書に実装方針と変更対象を反映する。

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant sendMessages
  participant PlatformTransport
  participant SSEParser
  participant JSONFallback
  sendMessages->>PlatformTransport: 共通リクエストボディでストリーミング送信
  PlatformTransport->>SSEParser: SSEチャンクを逐次転送
  SSEParser-->>sendMessages: 成功または分類済みエラー
  alt networkエラー
    sendMessages->>JSONFallback: 同じ本文でJSON POSTを1回実行
    JSONFallback-->>sendMessages: 確定応答またはnetworkエラー
  end
Loading

Poem

うさぎが跳ねて、SSEを受信
iOSはXHR、webはStream
networkならJSONへ一度だけ
429なら静かに止まる
にんじん色のテストも通る 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは、iOSのSSE受信をXHRへ切り替え、非ストリーミングへフォールバックする主要変更を明確に示しています。
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 fix/ios-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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/hooks/useDestinationAgent.test.ts (1)

830-839: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

フォールバック側の挙動も明示してください。

このテストは getSessionTokenMock に 2 回だけ null を設定します。3 回目の呼び出しは既定のモックへ戻ります。そのため sendViaJson はトークンを取得し、既定の失敗する globalThis.fetch を呼びます。結果の network はフォールバック失敗によるものであり、トークン取得失敗によるものではありません。

fallbackFetchMock の呼び出し回数を検証すると、テストの意図が明確になります。

♻️ 提案する追加アサーション
     expect(res).toEqual({ ok: false, error: 'network' });
     expect(FakeXhr.instances).toHaveLength(0);
+    // ストリーミングが network で終わるためフォールバックは 1 回走る
+    expect(fallbackFetchMock).toHaveBeenCalledTimes(1);
🤖 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 830 - 839, Update the
test around renderSendMessages to explicitly assert the fallback fetch behavior
by verifying fallbackFetchMock’s invocation count after the response. Keep the
existing null token setup and network result assertions, while making clear that
the third token attempt reaches sendViaJson and triggers the fallback fetch.
🤖 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.

Inline comments:
In `@docs/spec/ai-agent/architecture.md`:
- Around line 684-685: フォールバック時の表示説明を、送信時のプレースホルダに限定しない内容へ更新してください。`delta` 後に
`done` なしで `network`
へ遷移する場合は既存の部分テキストが表示されたままフォールバックし、最終的に確定値へ置き換わる実装を、`onDelta` / `onToolStart`
の呼び出し制約と併せて記述してください。

In `@src/hooks/useDestinationAgent.test.ts`:
- Around line 812-828: Move fake-timer cleanup for the tests around sendMessages
into an afterEach hook, ensuring jest.useRealTimers() runs even when an
assertion fails. Remove the inline restoration from the timeout test while
preserving its existing timeout, abort, and fallback assertions.

---

Nitpick comments:
In `@src/hooks/useDestinationAgent.test.ts`:
- Around line 830-839: Update the test around renderSendMessages to explicitly
assert the fallback fetch behavior by verifying fallbackFetchMock’s invocation
count after the response. Keep the existing null token setup and network result
assertions, while making clear that the third token attempt reaches sendViaJson
and triggers the fallback fetch.
🪄 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: af2f60f5-0d07-423c-b670-a4afdea52463

📥 Commits

Reviewing files that changed from the base of the PR and between 93fd732 and 7422727.

📒 Files selected for processing (4)
  • docs/spec/ai-agent/architecture.md
  • patches/expo+55.0.26.patch
  • src/hooks/useDestinationAgent.test.ts
  • src/hooks/useDestinationAgent.ts

Comment thread docs/spec/ai-agent/architecture.md Resolved
Comment thread src/hooks/useDestinationAgent.test.ts Resolved
@TinyKitten

Copy link
Copy Markdown
Member Author

Fixes Applied Successfully

Fixed 3 file(s) based on 2 CodeRabbit feedback item(s).

Files modified:

  • docs/spec/ai-agent/architecture.md(フォールバック中の表示記述を実装に合わせて修正。同旨のコードコメントも更新)
  • src/hooks/useDestinationAgent.ts
  • src/hooks/useDestinationAgent.test.ts(jest.useRealTimers() を afterEach へ移動)

Commit: 3ff09cb1e

The latest autofix changes are on the fix/ios-agent-streaming branch.

@TinyKitten
TinyKitten merged commit 05ae4b7 into dev Jul 31, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the fix/ios-agent-streaming branch July 31, 2026 09:55
@TinyKitten TinyKitten mentioned this pull request Jul 31, 2026
5 of 9 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Aug 12, 2026
4 of 9 tasks
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