Skip to content

Feature: Collaborative Draft Editing

Overview

Collaborative Draft Editing enables multiple team members to work together in real-time on email replies within a thread. Using Conflict-free Replicated Data Type (CRDT) technology via Yjs, team members can simultaneously edit the same draft without conflicts, seeing each other's changes instantly.

Feature Purpose

Complex customer inquiries often require input from multiple team members (support agents, specialists, managers). Instead of email ping-pong or offline document editing, this feature brings Google Docs-style collaboration directly into the email workflow, enabling faster and higher-quality responses.

User Value Proposition

For Support Teams:

  • Collaborate on complex responses without leaving the thread
  • Get real-time help from subject matter experts
  • See colleagues' edits as they type
  • Avoid version conflicts and lost work
  • Work offline and sync when reconnected

For Subject Matter Experts:

  • Quickly review and enhance responses
  • Add technical details in real-time
  • Provide guidance without taking over the thread

For Team Leads:

  • Review responses before sending
  • Ensure consistency in customer communication
  • Coach team members in real-time

For Organizations:

  • Improve response quality through collaboration
  • Reduce response time for complex issues
  • Enable knowledge sharing in context
  • Maintain single source of truth for drafts

Key Capabilities

1. Create Shared Draft

Description: Start a draft reply that can be collaboratively edited by the team.

User Experience:

  • "Reply" button on any email in thread
  • Clicking creates draft with pre-filled content:
    • To: Original sender
    • Subject: "Re: [original subject]"
    • Body: Quoted original email
  • Draft appears in thread timeline
  • Draft editor opens immediately
  • Only one draft per thread at a time

Acceptance Criteria:

  • Draft created via API call
  • Pre-filled content includes proper email headers
  • Draft visible to all inbox users
  • Draft creation action recorded in timeline
  • Clicking reply on existing draft opens it (no duplicate)

2. Real-time Collaborative Editing

Description: Multiple users edit the same draft simultaneously with instant synchronization.

User Experience:

  • Multiple users can edit draft at same time
  • Changes appear within 100-500ms for remote users
  • No conflicts or overwrites (CRDT magic)
  • Cursor positions and selections visible
  • Each collaborator has a distinct color
  • Smooth editing experience (no lag)

Acceptance Criteria:

  • Changes sync via WebSocket
  • No character loss or duplication
  • Typing at same position merges correctly
  • Conflict-free editing guaranteed by Yjs
  • Works with 5+ simultaneous editors
  • Offline edits queue and sync when reconnected

3. Rich Text Formatting

Description: Format draft content with common text styling options.

User Experience:

  • Formatting toolbar with buttons:
    • Bold, Italic, Underline
    • Ordered/Unordered Lists
    • Links
    • Images (embed)
    • Blockquotes
  • Toolbar persists at bottom of draft
  • Keyboard shortcuts (Cmd/Ctrl+B for bold, etc.)
  • Format applies to selection or cursor
  • All formatting syncs to collaborators

Acceptance Criteria:

  • All formatting options work reliably
  • Formatting preserved when syncing
  • HTML output is clean and valid
  • Keyboard shortcuts match platform conventions
  • Formatting visible in preview mode (future)

4. Collaborative Awareness

Description: See who else is currently editing the draft.

User Experience:

  • User avatars shown in draft header with "Active users" status label
  • Presence indicators update when users join/leave sessions
  • Cursor positions visible with name labels (via TipTap CollaborationCursor)
  • Selection highlights show what others are selecting
  • Colors distinguish different users
  • User list updates when people join/leave

Acceptance Criteria:

  • Active users status displayed with role="status" and aria-label="Active users"
  • Avatars rendered as list items with unique aria-labels
  • Awareness updates within 1-1.5 seconds of user join/leave
  • Avatar count reflects actual number of active collaborators
  • No duplicate avatars (verified by unique aria-labels)
  • Presence persists during editing session (tested up to 5+ seconds)
  • Both users can actively edit the draft content

E2E Test Coverage:

  • Avatar display and counting (verifies exactly 2 users in test scenarios)
  • Real-time join/leave updates (simplified verification of avatar presence)
  • Concurrent interaction stability (awareness remains accurate during activity)
  • Extended session persistence (no stale avatars after 5 seconds)
  • Duplicate avatar prevention (checked via aria-label uniqueness)

Note: Cursor positions and selection highlights are implemented via TipTap's CollaborationCursor extension but are not currently verified in E2E tests due to the complexity of testing visual cursor indicators across browser contexts.

5. Subject Line Editing

Description: Edit the email subject line collaboratively.

User Experience:

  • Subject input field in draft header
  • Subject synced like body content (via Yjs)
  • Changes visible to all collaborators
  • Default subject from original email
  • Can clear/rewrite subject

Acceptance Criteria:

  • Subject stored in Yjs document metadata
  • Subject changes sync in real-time
  • Subject preserved when draft reopened
  • Subject included in sent email

6. Local Persistence

Description: Persist draft locally to survive browser refresh and offline work.

User Experience:

  • Draft content saved to browser IndexedDB
  • Content persists across page refreshes
  • Draft continues from last edit position
  • Offline edits queued and synced later
  • Old drafts cleaned up automatically

Acceptance Criteria:

  • IndexedDB persistence via y-indexeddb
  • Draft synced to IndexedDB within 1 second
  • Browser refresh restores draft state
  • Multiple drafts (different threads) stored separately
  • Cleanup removes drafts older than 7 days

7. Send Collaborative Draft

Description: Send the completed draft as an email.

User Experience:

  • "Send" button available to all collaborators
  • Button in toolbar and footer
  • Clicking send shows confirmation (future)
  • Draft converted to sent email
  • Sent email appears in thread timeline
  • Draft removed from view
  • All collaborators see draft disappear

Acceptance Criteria:

  • Send via API endpoint
  • Draft content and subject included
  • Email sent via mail system
  • Sent action recorded in timeline
  • Draft record updated to "sentDraft" type
  • IndexedDB draft cleared
  • WebSocket notifies all users

8. Close Draft Without Sending

Description: Cancel/discard draft without sending.

User Experience:

  • "Close draft" button (X icon) in header
  • Clicking prompts confirmation (future)
  • Draft removed from timeline
  • Draft data deleted
  • All collaborators see draft disappear

Acceptance Criteria:

  • Close via DELETE API endpoint
  • Draft record updated to "removed" type
  • Yjs document destroyed
  • IndexedDB draft cleared
  • WebSocket notifies all users
  • Action recorded in timeline

UI/UX Design

Draft Layout

┌──────────────────────────────────────────────┐
│ Shared draft started by John Doe  [X Close] │
├──────────────────────────────────────────────┤
│ To: customer@example.com                     │
│ Subject: [Re: Original Subject............] │
├──────────────────────────────────────────────┤
│                                              │
│ [Draft content with rich text editor...]    │
│ Dear customer,                               │
│                                              │
│ Thank you for contacting us. We are         │
│ reviewing your issue and will respond...    │
│                                              │
│                                              │
├──────────────────────────────────────────────┤
│ [B] [I] [U] [•] [1.] [🔗] [📷] [❝]          │
│                               [Send Button]  │
└──────────────────────────────────────────────┘

Collaboration Indicators

┌──────────────────────────────────────────────┐
│ Shared draft · Active: JD, JS, BJ           │
│                        └─ user avatars       │
└──────────────────────────────────────────────┘

In content:
Dear customer█John Doe,
           └─ cursor with name label

Visual Design

  • Draft has distinct border/background (light blue tint)
  • Toolbar buttons have hover states
  • User cursors show as vertical lines with name tags
  • Selections highlighted with semi-transparent color
  • Send button primary style (blue background)
  • Close button secondary style (gray)
  • Loading states during sync

Technical Implementation

Architecture

  • CRDT Engine: Yjs for conflict-free merging
  • Editor: TipTap (ProseMirror-based)
  • Sync: Custom WebSocket provider (ADR-0008)
  • Persistence: PostgreSQL (yjs_documents, ADR-0028) + IndexedDB
  • Real-time: WebSocket with awareness

API Endpoints

EndpointMethodPurpose
POST /threads/:inboxId/:threadId/draftPOSTCreate new draft
DELETE /threads/:inboxId/:threadId/draftDELETEClose/discard draft
POST /threads/:inboxId/:threadId/draft/sendPOSTSend draft as email

WebSocket Sync

Custom Yjs WebSocket Provider:

  • Path: /teams/ws
  • Document ID: Thread ID
  • Authentication: JWT in params
  • Syncs Yjs document updates
  • Broadcasts awareness (cursors, presence)
  • Handles reconnection with exponential backoff

Data Model

Draft Action:

{
  type: "draft",
  created_at: Date,
  data: {
    originalReply: {}, // Original mail object from reply
    mail: {
      to: [{displayName, email}],
      from: [{displayName, email}],
      subject: string,
      content: string
    },
    owner: {id, context},
    startedBy: {id, context}
  }
}

Yjs Document Structure:

{
  mailContent: Y.XmlFragment, // TipTap content
  meta: Y.Map({
    subject: string
  })
}

Sent Draft Action:

{
  type: "sentDraft",
  created_at: Date,
  data: {
    from: {id, context},
    id: string,         // Mail ID in sent folder
    folder: string      // Folder ID
  }
}

State Management

Draft Lifecycle:

  1. Create: API creates draft action → Frontend opens editor
  2. Edit: Yjs syncs changes via WebSocket
  3. Persist: Content saved to PostgreSQL + IndexedDB
  4. Send/Close: API updates action type → Frontend closes editor

Component Structure:

  • shared-draft.vue: Main draft component
  • editor-toolbar.vue: Formatting controls
  • TipTap extensions: StarterKit, Collaboration, Underline, Link, Image

Yjs Integration

Real-time Architecture: See Technical Patterns - Yjs/CRDT for details on conflict-free collaborative editing.

Draft-Specific Configuration:

  • TipTap Collaboration extension with field: 'mailContent'
  • Awareness tracks active collaborators
  • IndexedDB persistence: draft_${threadId}${timestamp}
  • WebSocket sync via custom provider (ADR-0008)

Performance

  • WebSocket keeps persistent connection
  • Binary Yjs updates for efficiency (< 1KB typical)
  • Debounced IndexedDB writes (1 second)
  • Throttled awareness broadcasts (100ms)
  • Lazy loading of draft content

Dependencies

  • Yjs: CRDT library (ADR-0007)
  • TipTap: Rich text editor
  • y-websocket: Base WebSocket provider (customized, ADR-0008)
  • y-indexeddb: Browser persistence
  • yjs_documents: Server persistence, one snapshot per thread
  • Thread Management (drafts belong to threads)
  • Email Integration (sending drafts)

Known Limitations

  • No draft templates (planned)
  • No spell check integration
  • No draft auto-save indicator
  • No @mentions or comments within draft
  • No draft preview before sending

Future Enhancements

  1. Draft Templates: Pre-defined response templates
  2. @Mentions: Notify specific team members
  3. Comments: Add review comments without editing content
  4. Version History: View/restore previous versions
  5. Auto-save Indicator: Show when last saved
  6. Draft Preview: Preview formatted email before sending
  7. Scheduled Send: Send draft at specific time
  8. Draft Permissions: Restrict who can edit/send
  9. Spell Check: Integrate browser spell check
  10. AI Assistance: Suggest improvements, tone analysis
  • Thread Management (context for drafts)
  • Email Integration (sending functionality)
  • Real-time Collaboration (awareness, WebSocket)
  • Assignment Workflow (draft ownership)
  • ADR-0007: Introduce Yjs to share state
  • ADR-0008: Use own WebSocket for Yjs
  • ADR-0006: Database layer (storing Yjs documents)

Success Metrics

  • 95% of collaborative drafts sent successfully
  • < 500ms latency for remote edits (p95)
  • Zero data loss from conflicts
  • 80% of complex responses use collaboration
  • Average 2.5 collaborators per draft
  • Sync success rate > 99.9%
  • User satisfaction > 4.5/5 for collaboration feature