# Specification: 008-team-chat

## Status

| Field | Value |
|-------|-------|
| **Created** | 2026-01-02 |
| **Current Phase** | ✅ IMPLEMENTATION COMPLETE |
| **Last Updated** | 2026-01-03 (All Phases Complete) |

### Implementation Progress

| Phase | Status | Completed |
|-------|--------|-----------|
| Phase 1: Foundation | ✅ COMPLETED | 2026-01-02 |
| Phase 2: Data Layer | ✅ COMPLETED | 2026-01-03 |
| Phase 3: Real-time | ✅ COMPLETED | 2026-01-03 |
| Phase 4: State Management | ✅ COMPLETED | 2026-01-03 |
| Phase 5: UI Widgets | ✅ COMPLETED | 2026-01-03 |
| Phase 6: Screens & Navigation | ✅ COMPLETED | 2026-01-03 |
| Phase 7: Integration & Validation | ✅ COMPLETED | 2026-01-03 |

### Final Validation Results (Phase 7)

| Metric | Result |
|--------|--------|
| **Unit Tests** | 904 tests passing |
| **Chat Tests** | 40 dedicated tests |
| **Static Analysis** | 0 issues |
| **Android Build** | ✅ APK built successfully |
| **iOS Build** | ✅ IPA built successfully |
| **Notification Navigation** | ✅ Updated for chat deep links |

## Documents

| Document | Status | Notes |
|----------|--------|-------|
| product-requirements.md | completed | Codex-reviewed, all blockers resolved |
| solution-design.md | completed | Codex-reviewed, all blockers resolved |
| implementation-plan.md | completed | Codex-reviewed, 7 phases, 220+ tasks, full TDD structure |

## Implementation Plan Codex Review (2026-01-02)

### Blockers Resolved
- ✅ Package path inconsistency (SDD said lib/, plan said packages/) - Updated SDD to match user decision
- ✅ Missing polling fallback (30s when Ably unavailable) - Added T3.5.15, T3.5.16
- ✅ Missing message action menu implementation - Added T5.3.5-T5.3.7 (menu, edit mode, delete dialog)

### Important Improvements Made
- ✅ Added AblyClient adapter for testability (T3.2.1-T3.2.3)
- ✅ Added Risks & Mitigations section with 7 identified risks
- ✅ Added analytics instrumentation tasks (T4.10.1-T4.10.10)
- ✅ Added push notification end-to-end tasks (T6.10.1-T6.10.6)
- ✅ Added integration checkpoints (T3.7, T4.8 vertical slice)
- ✅ Added "Done When" criteria to Phases 3 and 4
- ✅ Marked Phase 2 + Phase 3 as parallel execution opportunity
- ✅ Added search context interpretation note (load-until-found behavior)
- ✅ Added ChatMemberRemovedEvent for access revocation handling

### Final Phase Summary

| Phase | Focus | Task Groups | Parallel? |
|-------|-------|-------------|-----------|
| 1 | Foundation | 8 | T1.4 + T1.6 parallel |
| 2 | Data Layer | 8 | Can run parallel with Phase 3 |
| 3 | Real-time | 8 | Can run parallel with Phase 2 |
| 4 | State | 10 | Sequential |
| 5 | Widgets | 9 | T5.2-T5.7 all parallel |
| 6 | Screens | 11 | Some parallel possible |
| 7 | Validation | 13 | Sequential |

**Estimated Complexity**: High (chat is a full-featured module)
**Test Coverage Requirement**: ≥80% for new code

## Codex PRD Review (2026-01-02)

### Blockers Resolved
- ✅ Channel provisioning/management defined (permissions matrix, lifecycle)
- ✅ Read receipt behavior specified (500ms viewport rule, privacy, multi-device)
- ✅ Notification behavior spec added (priority rules, batching, mention overrides)
- ✅ OpenAPI spec location documented (`docs/api/staff-chat-mobile-openapi.yaml`)

### Improvements Made
- Added permissions matrix (role → action mapping)
- Added channel types and lifecycle documentation
- Added comprehensive edge cases (40+ scenarios)
- Added operational metrics with targets
- Refined KPI definitions with measurement methods
- Added dependencies table with status
- Added "Cost of Status Quo" with estimated impact

### Remaining Enhancements (non-blocking)
- Empty state illustration: Design team to provide
- Analytics pipeline ownership: TBD with platform team

**Status values**: `pending` | `in_progress` | `completed` | `skipped`

## Decisions Log

| Date | Decision | Rationale |
|------|----------|-----------|
| 2026-01-02 | Shared Flutter package | Create `buyerkiosk_chat` package with models, services, core logic for both Team and Live apps |
| 2026-01-02 | Start with PRD | Define requirements and UI decisions before technical design |
| 2026-01-02 | Custom UI (not chatview) | Full control for consistency across apps |
| 2026-01-02 | WhatsApp-style bubbles | Familiar pattern, own messages right (purple), others left (gray) |
| 2026-01-02 | Role mentions (@managers, @staff) | Added to Phase 1 scope per user request |
| 2026-01-02 | Manual channel pinning | Long-press to pin, no auto-pin |
| 2026-01-02 | Read-only offline mode | Simplify v1, no offline message queue |
| 2026-01-02 | Dark mode required | Follow system preference at launch |
| 2026-01-02 | ADR-1: Separate Ably Service | Keep AblyRealtimeService in core/services/, separate from ChatRepository |
| 2026-01-02 | ADR-2: Stream-based updates | Use Dart Streams for real-time event flow (reactive, composable) |
| 2026-01-02 | ADR-3: Optimistic updates | Use clientMessageId (UUID) for instant UX with server confirmation |
| 2026-01-02 | ADR-4: Composite state | Single ChatNotifier with composite state (follows AuthNotifier pattern) |
| 2026-01-02 | ADR-5: In-memory cache only | No local database for v1 (simpler, aligns with read-only offline) |
| 2026-01-02 | Create package scaffolding now | Set up `packages/buyerkiosk_chat/` structure during Phase 1 (vs. post-MVP) |
| 2026-01-02 | Include deferred feature model fields | Add replyToId, attachments fields to models now; defer UI implementation |
| 2026-01-02 | TabBarView in ChatScreen | Channels \| Mentions as tabs within single screen (not separate routes) |

## Codex Phase 4 Code Review (2026-01-03)

### Review Scope
Code review of Phase 4 (State Management) implementation including ChatNotifier, ChatCompositeState, and chat providers.

### Critical Issues Fixed
- ✅ `enterChannel()` unsubscribe order bug - captured previousChannelId before updating state
- ✅ Optimistic message dropped while loading - check if message exists in state before ignoring

### Important Improvements Made
- ✅ Reaction aggregation idempotency - prevent duplicate Ably events adding same user
- ✅ Membership removal cleanup - call `_unsubscribeFromActiveChannel()` on access revocation
- ✅ Pin order implementation - prepend newly pinned channels, sort by pinOrder in `sortedChannels`
- ✅ Use storeProvider for typeNum - respects user's multi-store selection vs arbitrary first store
- ✅ sortedMessagesProvider rebuild efficiency - watch messagesStateProvider instead of composite state
- ✅ Channel preview update - always update lastMessagePreview for consistency

### Package Updates
- Added `pinOrder` field to Channel entity for pin sort order

---

## Codex SDD Review (2026-01-02)

### Review Process
SDD reviewed by Codex against PRD for alignment, architecture soundness, and completeness.

### Blockers Resolved
- ✅ Added missing model definitions (AttachmentModel, ReactorModel, MentionReferenceModel, MessageSender)
- ✅ Fixed offline mode inconsistency (confirmed read-only per PRD)
- ✅ Added comprehensive Shared Package Plan with structure and versioning

### Important Improvements Made
- ✅ Added channel management screens (create_channel, channel_settings, member_profile_sheet)
- ✅ Added Ably presence mitigation strategy for >100 member channels
- ✅ Added complete analytics event mapping (PRD → Implementation)
- ✅ Added detailed pin/unpin UX specification
- ✅ Added read receipt semantics (high-water mark approach)
- ✅ Added notification grouping clarification (backend responsibility)
- ✅ Added token capability scope and access revocation handling
- ✅ Added PRD Traceability Matrix with all features mapped
- ✅ Added Appendix for deferred "Could Have" features

### Enhancements (Documented but Not Blocking)
- Profile card popup: Bottom sheet design added
- Polling fallback: Strategy noted in Quality Requirements
- Permissions matrix: Backend enforces; client respects API errors

### Deferred to Post-MVP
- F11: Image Attachments (models defined, UI deferred)
- F12: Reply Threading (replyToId field only, quote UI deferred)
- F13: Link Previews (not designed)

## Context

**Feature**: Full-featured in-app team chat

**API Specification**: `docs/api/staff-chat-mobile-openapi.yaml` (1,224 lines, 19 endpoints)

**Key Capabilities**:
- Channels (list, create, get details, settings, mute)
- Messages (send, edit, delete, search, pagination)
- Reactions (add/remove emoji reactions)
- Members (list, add, remove - manager+ only)
- Read receipts (mark as read)
- Mentions (@username inbox)
- Attachments (download signed URLs)
- Real-time (Ably token for live updates)

**UI Package**: chatview (pub.dev) - provides ChatList, ChatView widgets with reactions, replies, typing indicators

**Coordination Requirement**: Must sync implementation with BuyerKiosk Live Flutter app (`../buyerkiosk-live-flutter`) so both apps share the same chat experience.

**Coordination Finding**:
- Both apps use identical architecture: Riverpod + Freezed + Dio
- Both have placeholder chat screens
- BuyerKiosk Live already has Ably integration for push notifications
- Same OpenAPI spec exists in both repos

---
*This file is managed by the specification-management skill.*
