All files / web/src/hooks useBackgroundTask.ts

97.78% Statements 221/226
80% Branches 24/30
100% Functions 2/2
97.78% Lines 221/226

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 2271x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 54x 19x 2x 2x       2x 2x 2x 2x 2x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 3x 3x 3x 3x 17x 17x 17x 17x 19x     17x 17x 1x 1x 17x 17x 17x 1x 1x 1x 17x 17x 17x 17x 7x 7x 7x 7x 7x 7x 17x 17x 17x 17x 6x 5x 5x 5x 5x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 5x 1x 1x 5x 5x 5x 6x 17x 17x 17x 17x 2x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 54x 54x 54x 1x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x  
'use client'
 
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import type { TaskStatus } from '@/db/schema/background-tasks'
 
/**
 * Event received from the task system
 */
export interface TaskEvent {
  taskId: string
  eventType: string
  payload: unknown
  createdAt: Date | string
  replayed?: boolean
}
 
/**
 * State of a background task
 * Note: `input` is intentionally omitted - it can contain large data (e.g., base64 images)
 * and is not needed by clients for progress tracking
 */
export interface TaskState<TOutput = unknown> {
  id: string
  type: string
  status: TaskStatus
  progress: number
  progressMessage: string | null
  output: TOutput | null
  error: string | null
  createdAt: Date | string
  startedAt: Date | string | null
  completedAt: Date | string | null
  events: TaskEvent[]
}
 
interface UseBackgroundTaskResult<TOutput = unknown> {
  /** Current task state (null if not yet loaded) */
  state: TaskState<TOutput> | null
  /** Whether connected to the socket */
  isConnected: boolean
  /** Whether currently loading initial state */
  isLoading: boolean
  /** Error message if subscription failed */
  error: string | null
  /** Cancel the task */
  cancel: () => void
}
 
/**
 * Hook to subscribe to background task updates via Socket.IO
 *
 * Provides real-time updates for long-running tasks with automatic event replay
 * on page reload.
 *
 * @param taskId - The task ID to subscribe to (null to not subscribe)
 * @returns Task state, connection status, and control methods
 *
 * @example
 * ```tsx
 * function TaskProgress({ taskId }: { taskId: string }) {
 *   const { state, cancel } = useBackgroundTask<MyOutput>(taskId)
 *
 *   if (!state) return <div>Loading...</div>
 *
 *   return (
 *     <div>
 *       <p>Status: {state.status}</p>
 *       <p>Progress: {state.progress}%</p>
 *       {state.status === 'running' && <button onClick={cancel}>Cancel</button>}
 *       {state.output && <pre>{JSON.stringify(state.output)}</pre>}
 *     </div>
 *   )
 * }
 * ```
 */
export function useBackgroundTask<TOutput = unknown>(
  taskId: string | null
): UseBackgroundTaskResult<TOutput> {
  const [state, setState] = useState<TaskState<TOutput> | null>(null)
  const [isConnected, setIsConnected] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const socketRef = useRef<Socket | null>(null)
 
  useEffect(() => {
    if (!taskId) {
      // Clean up if taskId becomes null
      if (socketRef.current) {
        socketRef.current.disconnect()
        socketRef.current = null
      }
      setIsConnected(false)
      setState(null)
      setError(null)
      return
    }
 
    setIsLoading(true)
    setError(null)
 
    // Create socket connection
    const socket = createSocket({
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5,
    })
    socketRef.current = socket
 
    const handleConnect = () => {
      console.log('[useBackgroundTask] Connected, subscribing to task:', taskId)
      setIsConnected(true)
      socket.emit('task:subscribe', taskId)
    }
 
    socket.on('connect', handleConnect)
 
    // If already connected (shared Manager), trigger manually
    if (socket.connected) {
      handleConnect()
    }
 
    socket.on('disconnect', () => {
      console.log('[useBackgroundTask] Disconnected')
      setIsConnected(false)
    })
 
    socket.on('connect_error', (err) => {
      console.error('[useBackgroundTask] Connection error:', err)
      setError('Failed to connect to task server')
      setIsLoading(false)
    })
 
    // Handle initial task state
    socket.on('task:state', (task: TaskState<TOutput>) => {
      console.log('[useBackgroundTask] Received task state:', task.status)
      setState((prev) => ({
        ...task,
        events: prev?.events ?? [],
      }))
      setIsLoading(false)
    })
 
    // Handle task events (real-time and replayed)
    socket.on('task:event', (event: TaskEvent) => {
      if (event.taskId !== taskId) return
 
      console.log(
        '[useBackgroundTask] Received event:',
        event.eventType,
        event.replayed ? '(replayed)' : ''
      )
 
      setState((prev) => {
        if (!prev) return prev
 
        const newState = {
          ...prev,
          events: [...prev.events, event],
        }
 
        // Update state based on event type
        switch (event.eventType) {
          case 'started':
            newState.status = 'running'
            break
          case 'progress': {
            const payload = event.payload as { progress: number; message?: string }
            newState.progress = payload.progress
            newState.progressMessage = payload.message ?? null
            break
          }
          case 'completed': {
            const payload = event.payload as { output: TOutput }
            newState.status = 'completed'
            newState.progress = 100
            newState.output = payload.output
            break
          }
          case 'failed': {
            const payload = event.payload as { error: string }
            newState.status = 'failed'
            newState.error = payload.error
            break
          }
          case 'cancelled':
            newState.status = 'cancelled'
            break
        }
 
        return newState
      })
    })
 
    // Handle errors
    socket.on('task:error', (data: { taskId: string; error: string }) => {
      if (data.taskId === taskId) {
        console.error('[useBackgroundTask] Error:', data.error)
        setError(data.error)
        setIsLoading(false)
      }
    })
 
    return () => {
      console.log('[useBackgroundTask] Cleaning up')
      socket.emit('task:unsubscribe', taskId)
      socket.disconnect()
      socketRef.current = null
    }
  }, [taskId])
 
  const cancel = useCallback(() => {
    if (socketRef.current && taskId) {
      socketRef.current.emit('task:cancel', taskId)
    }
  }, [taskId])
 
  return {
    state,
    isConnected,
    isLoading,
    error,
    cancel,
  }
}