refactor(ai-chat): extract useChatSession hook + lock the id lifecycle with tests

Addresses the 2nd PR #138 review (test debt + the Variant-B architecture ask).

The new→persisted chat id lifecycle (mount key, both adoption paths, the
history-load latch, the render-phase reconciler, onTurnFinished) is moved out of
the 768-line window into a new useChatSession hook driven by a pure
threadSessionReducer (reconcile/adopt), so adopt-vs-switch is one explicit
dispatch point and the scattering the review flagged is gone (window: 768→~620).

Tests (the blockers):
- use-chat-session.test.tsx — hook-level locks incl. the #137 regression
  (adopts the authoritative streamed id 'A', NOT chats.items[0]='B' — fails on
  the old heuristic), the error-path fallback (arm/adopt/ambiguous/add+delete),
  the disarm-on-reconcile lock (a fallback armed then switched away must not be
  adopted by a late refetch), in-place-adopt-keeps-key vs external-switch-remount,
  and the waitingForHistory latch.
- extractServerChatId (reading message.metadata.chatId) and newlyAddedChatIds
  extracted as pure helpers with unit tests; threadSessionReducer tested.

Cleanups: single canonical #137 explanation in adopt-chat-id.ts (other sites
reference it); fallback effect computes the set diff once; invalidate callbacks
memoized; redundant invariant tests folded.

Behavior preserved — re-verified live (z.ai glm-5.2): new-chat adopt + 2nd turn
in the same row, no mid-conversation remount, two-tab race leak-free, switch to
an existing chat reseeds full history, reload restores history.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
claude code agent 227
2026-06-23 02:25:52 +03:00
parent ba90147749
commit f59ca3cb0d
9 changed files with 556 additions and 213 deletions

View File

@@ -562,12 +562,9 @@ export class AiChatService {
}
/**
* Compute the `messageMetadata` payload for the streamed assistant UI message.
* The AI SDK invokes `messageMetadata` on each stream part (ai@6); we attach the
* authoritative `chatId` ONLY on the `start` part so it reaches the client at the
* very first chunk (as `message.metadata.chatId`). The client adopts THAT id for a
* new chat instead of guessing the newest chat in its list — fixing the two-tab
* adoption race (#137). Returning undefined for any non-start part adds no metadata.
* Attach the authoritative `chatId` to the streamed assistant message's `start`
* part (as `message.metadata.chatId`) so the client can adopt the real id for a
* new chat. See the client's adopt-chat-id.ts for the full #137 design.
*/
export function chatStreamStartMetadata(
part: { type: string },