# Phase 6 Plan 2: React Architecture & Implementation Roadmap Summary

**Designed React architecture, Redux state, and created implementation roadmap for Phases 7-11**

**Date:** 2026-01-26
**Status:** Complete
**Commits:** 192703f59, 3206c1268, df87713ff

---

## Accomplishments

### Task 1: Design Component Architecture ✅

**File Created:** `.planning/phases/06-session-chat-research-design/CHAT_COMPONENT_DESIGN.md` (954 lines)

**Component Hierarchy Designed:**
- **JKSessionChatButton** - Top nav button with unread badge
- **JKSessionChatWindow** - Main window wrapper (WindowPortal)
  - **JKChatHeader** - Title bar with close button
  - **JKChatMessageList** - Scrollable container with auto-scroll
    - **JKChatMessage** - Single message (avatar, name, text, timestamp)
    - **JKChatLoadingSpinner** - Loading indicator
    - **JKChatEmptyState** - Empty state display
  - **JKChatComposer** - Message input and send button

**Key Design Decisions:**
- **WindowPortal Integration:** Reuse existing component (no modifications needed)
- **Props vs Redux Matrix:** Heavy Redux usage (minimal props)
- **Auto-Scroll Logic:** Track `isUserScrolling` state, disable auto-scroll when user scrolls up
- **Enter-to-Send:** Enter sends, Shift+Enter adds newline
- **Component File Structure:** `jam-ui/src/components/client/chat/`

**Patterns Applied:**
- Follows JamTrack player architecture (main component + sub-components)
- Matches Backing Track patterns (WindowPortal, Redux-heavy)
- Component lifecycle: Mount → Fetch history → Mark as read → Unmount

---

### Task 2: Design Redux State and WebSocket Integration ✅

**File Created:** `.planning/phases/06-session-chat-research-design/CHAT_REDUX_DESIGN.md` (1,132 lines)

**Redux State Structure:**
- **sessionChatSlice** (new slice)
  - `messagesByChannel`: Keyed by channel ID for efficient lookup
  - `unreadCounts`: Per-channel unread tracking (NEW functionality)
  - `lastReadAt`: Timestamps for read state (localStorage persistence)
  - `fetchStatus` / `sendStatus`: Per-channel operation status
  - `isWindowOpen`: Window state (UI)

**Async Thunks (3):**
1. **fetchChatHistory** - Load message history via REST API
2. **sendMessage** - Send new message with optimistic update
3. **markMessagesAsRead** - Mark as read (future server-side tracking)

**Reducers (7):**
1. **addMessageFromWebSocket** - Handle real-time messages, deduplicate by `msg_id`
2. **setActiveChannel** - Switch between global/session/lesson
3. **openChatWindow** - Reset unread count, mark as read
4. **closeChatWindow** - Close window state
5. **markAsRead** - Client-side read tracking with localStorage
6. **incrementUnreadCount** - Increment on message receive
7. **setWindowPosition** - Save window position

**Selectors (8 memoized with Reselect):**
- `selectChatMessages`, `selectUnreadCount`, `selectTotalUnreadCount`
- `selectIsChatWindowOpen`, `selectActiveChannel`
- `selectFetchStatus`, `selectSendStatus`, `selectSendError`

**WebSocket Integration:**
- **CHAT_MESSAGE Handler** in `useSessionWebSocket` hook
- Protocol Buffer to Redux format conversion
- Unread count increment logic (if window closed or different channel)
- Message deduplication by `msg_id`

**Read/Unread Tracking System (NEW):**
- **Client-side tracking** with localStorage persistence
- Store `lastReadAt` timestamp per channel
- Calculate unread count: messages with `createdAt > lastReadAt`
- Reset on window open or channel switch
- **Server-side tracking deferred** to future milestone (new API endpoint needed)

---

### Task 3: Create Implementation Roadmap ✅

**File Created:** `.planning/phases/06-session-chat-research-design/IMPLEMENTATION_ROADMAP.md` (1,138 lines)

**Phase Breakdown (11-13 plans estimated):**

**Phase 7: Chat Infrastructure & State Management (3 plans)**
- Plan 7.1: Redux Slice & Core Reducers (TDD)
- Plan 7.2: Async Thunks & API Integration (TDD)
- Plan 7.3: WebSocket Integration & Selectors (TDD)

**Phase 8: Chat Window UI & Message Display (3 plans)**
- Plan 8.1: Chat Window Shell & WindowPortal Integration
- Plan 8.2: Message List & Auto-Scroll
- Plan 8.3: Chat Button & Unread Badge

**Phase 9: Message Composition & Sending (2 plans)**
- Plan 9.1: Message Composer & Validation (TDD)
- Plan 9.2: Send Message & Real-Time Delivery (TDD)

**Phase 10: Read/Unread Status Management (2 plans)**
- Plan 10.1: Unread Tracking & Badge Updates (TDD)
- Plan 10.2: Channel Switching & Read State Sync

**Phase 11: Chat Finalization & Polish (3 plans)**
- Plan 11.1: Error Handling & Retry Logic
- Plan 11.2: Performance Optimization & Accessibility
- Plan 11.3: UAT & Final Integration Testing

**Estimated Effort:**
- **11-13 plans, 28-32 tasks total**
- **Complexity:** 1.5-2x more than Backing Track (Phase 3: 3 plans)
- **Complexity:** 0.6x less than JamTrack (Phase 5: 9 plans)

**Risk Analysis:**
- **2 HIGH Risks:** WebSocket message deduplication, localStorage persistence edge cases
- **4 MEDIUM Risks:** Auto-scroll conflicts, multi-tab state sync, API error handling, WindowPortal styling
- **2 LOW Risks:** Character count validation, timestamp formatting performance

**TDD Strategy:**
- **Phase 7:** 100% TDD (all data layer)
- **Phase 8:** 50% TDD (component behavior, skip styling)
- **Phase 9:** 100% TDD (composition logic)
- **Phase 10:** 100% TDD (unread tracking)
- **Phase 11:** 70% TDD (error handling, skip performance optimizations)

**Testing Strategy:**
- **Unit Tests:** 80%+ coverage (Redux, API, WebSocket)
- **Integration Tests:** 7 test files covering all user flows
- **E2E Tests:** Complete workflow + multi-user scenario
- **UAT:** 40+ test cases across 9 categories

**Critical Decisions (5):**
1. **Message Virtualization:** Defer until needed (simple MVP)
2. **Optimistic UI Updates:** Implement for better UX
3. **Unread Count Persistence:** Store in localStorage
4. **Multi-Tab State Sync:** Defer to next milestone
5. **Auto-Scroll Strategy:** Track scroll position (smart)

**Deferred Features (Next Milestone):**
- Server-side read/unread tracking
- File attachments
- Message search/filtering
- Message editing/deletion
- Typing indicators
- Emoji picker
- Multi-channel tabs UI
- Notification sounds
- Desktop notifications

---

## Decisions Made

### 1. Component Architecture

**JKSessionChatWindow follows JamTrack pattern:**
- Main component wraps WindowPortal
- Sub-components for modularity (Header, MessageList, Message, Composer)
- Props vs Redux: Heavy Redux (minimal props, only callbacks)

**Auto-Scroll Logic:**
- Track `isUserScrolling` state
- Disable auto-scroll if user scrolls up
- Re-enable when user scrolls to bottom
- Matches legacy ChatWindow behavior

**WindowPortal for Modeless Dialog:**
- Reuse existing component (no modifications)
- 400x600px dimensions (similar to Metronome)
- User-repositionable (WindowPortal handles)

---

### 2. Redux State Architecture

**sessionChatSlice (New Slice):**
- Multi-channel storage: `messagesByChannel[channelId]`
- Efficient lookup by channel ID (no filtering needed)
- Unread counts per channel (NEW functionality)
- localStorage persistence for `lastReadAt` timestamps

**Message Deduplication:**
- Deduplicate by `msg_id` in `addMessageFromWebSocket` reducer
- Prevents duplicate UI rendering on WebSocket reconnect
- Unit tests for deduplication logic

**Async Thunk Pattern:**
- Follow existing patterns from mediaSlice (Phase 5)
- Error handling: pending/fulfilled/rejected states
- Extra reducers for state updates

---

### 3. Read/Unread Tracking Strategy

**Client-Side Tracking (Phase 6):**
- Store `lastReadAt` timestamp per channel in Redux
- Persist to localStorage for cross-session consistency
- Calculate unread count on message receive (if window closed)
- Reset on window open or channel switch

**Server-Side Tracking (Future):**
- Create new `chat_message_reads` table
- API endpoint: `PUT /api/chat/mark_read`
- Cross-device synchronization
- Per-message read receipts (optional)

**Rationale:**
- Client-side simpler for MVP
- Server-side more robust but requires schema changes
- Acceptable tradeoff: Unread counts reset on logout (MVP)

---

### 4. Multi-Channel Architecture

**Channel Keying:**
- Global: `'global'`
- Session: `'session-{sessionId}'`
- Lesson: `'lesson-{lessonId}'`

**Benefits:**
- Efficient lookups (no filtering)
- Supports multiple sessions (future: multi-session jam)
- Clean separation of global vs session messages

---

### 5. WebSocket Integration

**CHAT_MESSAGE Handler:**
- Add to existing `useSessionWebSocket` hook
- Convert Protocol Buffer format to Redux format
- Dispatch `addMessageFromWebSocket()` action
- Increment unread count if window closed

**No Modifications to JamServer:**
- `CHAT_MESSAGE` type already defined
- Use existing `registerMessageCallback` API
- Cleanup automatic (unregister on unmount)

---

### 6. TDD Approach

**100% TDD for Data Layer:**
- Redux reducers, async thunks, selectors
- API client methods
- WebSocket handlers
- Validation logic

**50-70% TDD for UI:**
- Component behavior (send, auto-scroll, unread badge)
- Keyboard handling
- Error handling
- Skip styling, visual appearance

**Rationale:**
- CLAUDE.md requires TDD for jam-ui
- Data layer has clear test criteria
- UI behavior has measurable outcomes
- Styling is visual, hard to test programmatically

---

## Files Created/Modified

**Created:**
- `.planning/phases/06-session-chat-research-design/CHAT_COMPONENT_DESIGN.md` (954 lines)
- `.planning/phases/06-session-chat-research-design/CHAT_REDUX_DESIGN.md` (1,132 lines)
- `.planning/phases/06-session-chat-research-design/IMPLEMENTATION_ROADMAP.md` (1,138 lines)

**Total:** 3,224 lines of documentation

**Commits:**
- `192703f59` - feat(06-02): design session chat component architecture
- `3206c1268` - feat(06-02): design Redux state and WebSocket integration for chat
- `df87713ff` - feat(06-02): create implementation roadmap for Phases 7-11

---

## Key Insights

### 1. Chat is Simpler Than JamTrack

**No Native Client Integration:**
- Chat is purely web-based (REST API + WebSocket)
- JamTrack uses jamClient.* methods (complex download/sync)
- Chat state machine simpler (3 states vs 6-state machine)

**Implication:** Phase 7-11 should be faster than Phase 5 (JamTrack)

---

### 2. Read/Unread Tracking is NEW

**Critical Finding:** Session/global chat has NO persistent tracking in legacy.

**Design from Scratch:**
- No legacy patterns to follow
- Must align with lesson chat patterns (teacher_unread_messages, student_unread_messages)
- Client-side tracking acceptable for MVP
- Server-side tracking deferred to next milestone

**Implication:** This is NEW functionality, not just porting legacy

---

### 3. WindowPortal is Proven Pattern

**Already Used By:**
- Metronome popup (Phase 2)
- JamTrack player popup (Phase 5)

**Benefits:**
- No modifications needed (reuse as-is)
- Auto-handles styling, cleanup, lifecycle
- User-repositionable, modeless dialog

**Implication:** Phase 8 should be straightforward (no WindowPortal debugging)

---

### 4. Multi-Channel Complexity

**Legacy Pattern:**
- Single store manages all channels (global, session, lesson_N)
- Active channel tracked in state
- Messages keyed by channel ID

**Design Decision:**
- Follow legacy pattern (proven to work)
- `messagesByChannel[channelId]` for efficient lookup
- Avoid filtering on every render

**Implication:** Slightly more complex than single-channel, but more scalable

---

### 5. TDD Methodology Required

**CLAUDE.md Mandate:**
- All jam-ui code changes MUST follow TDD
- Test-first for data layer
- Test component behavior (not appearance)

**Phase 7-11 Strategy:**
- Phase 7: 100% TDD (foundation)
- Phase 8-10: Mixed TDD (behavior, skip styling)
- Phase 11: 70% TDD (error handling, skip performance)

**Implication:** Testing effort is significant (~30-40% of implementation time)

---

## Issues Encountered

### None

All three tasks completed successfully based on Phase 6 Plan 1 documentation (CHAT_LEGACY.md, CHAT_API.md, CHAT_REACT_PATTERNS.md) and prior phase patterns (Phase 3, Phase 4, Phase 5).

---

## Next Phase Readiness

**Phase 6 Complete!** Ready for Phase 7 (Chat Infrastructure & State Management)

**Design Artifacts Created:**
- ✅ Component architecture (8 components, 3 levels deep)
- ✅ Redux state structure (sessionChatSlice with 3 async thunks, 7 reducers, 8 selectors)
- ✅ WebSocket integration (CHAT_MESSAGE handler)
- ✅ Read/unread tracking system (client-side with localStorage)
- ✅ Implementation roadmap (11-13 plans, 28-32 tasks)
- ✅ Risk analysis (2 HIGH, 4 MEDIUM, 2 LOW risks with mitigation)
- ✅ Testing strategy (unit, integration, E2E, 40+ UAT cases)
- ✅ TDD strategy (per CLAUDE.md requirements)

**Inputs for Phase 7:**
- CHAT_COMPONENT_DESIGN.md → Component specs for UI implementation
- CHAT_REDUX_DESIGN.md → Redux state structure for data layer
- CHAT_REACT_PATTERNS.md → Available patterns and gaps
- CHAT_API.md → API contracts to implement
- CHAT_LEGACY.md → Legacy patterns to modernize

**Phase 7 Execution Path:**
1. `/gsd:plan-phase 7` to create executable PLAN.md files
2. Refine 3 preliminary plans based on config depth
3. Execute Plan 7.1: Redux Slice & Core Reducers (TDD)
4. Execute Plan 7.2: Async Thunks & API Integration (TDD)
5. Execute Plan 7.3: WebSocket Integration & Selectors (TDD)

**Architectural Foundation Solid:**
- Component design follows established patterns (JamTrack, Backing Track)
- Redux extensions logical and well-scoped
- Risk mitigation strategies clear
- Testing strategy comprehensive
- Dependencies mapped, critical path identified
- TDD strategy aligned with CLAUDE.md

**Ready for implementation!**

---

## Documentation Quality

**Strengths:**
- ✅ Comprehensive coverage (all architectural aspects)
- ✅ Clear component hierarchy with props interfaces
- ✅ Detailed Redux state structure with TypeScript interfaces
- ✅ WebSocket integration patterns documented
- ✅ Read/unread tracking state machine defined
- ✅ Risk analysis with mitigation strategies
- ✅ TDD strategy per CLAUDE.md requirements
- ✅ 40+ UAT test cases defined
- ✅ Comparison to prior phases (JamTrack, Backing Track)

**Future Reference:**
- These documents will serve as primary reference during Phases 7-11
- Can be shared with other developers for onboarding
- Can be used to compare jam-ui implementation with legacy
- Phase 7 plans can reference these docs for implementation details

---

**Phase 6 Complete!**
**Ready for Phase 7: Chat Infrastructure & State Management**

**Next Command:** `/gsd:plan-phase 7`

---

*Phase: 06-session-chat-research-design*
*Completed: 2026-01-26*
