All files / main/services timerService.ts

91.94% Statements 137/149
87.2% Branches 75/86
92.3% Functions 24/26
92.85% Lines 130/140

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385                                                                            1x 18x   1x 6x         6x               27x 27x 27x   27x     27x 27x 27x 27x   27x 6x 6x 6x             6x 3x 3x                 3x 1x                   6x 6x     21x   21x 19x 19x 19x     2x       2x         2x                 2x 1x                 2x 2x       18x 18x 18x 1x   17x 17x 17x   18x   16x             16x               16x 16x       1x 1x 1x       6x 6x 1x     5x 4x 4x   4x           4x           4x 4x       3x 3x 3x 3x   2x 2x   2x           2x           2x 2x                                 2x 2x 2x 2x       1x   1x 1x 1x     1x 1x       3x 3x   3x       3x 3x   3x 3x                 3x 3x   3x 3x 3x   3x 1x     2x 2x       3x       3x 3x       3x 3x 3x   3x 3x         20x 6x     25x 14x 2x     12x       26x     26x       55x 55x             18x 18x 4x   3x 3x                   2x 2x   2x 5x 3x 2x         159x     159x       55x 55x      
import { EventEmitter } from 'node:events'
import {
  completeTimer,
  createIdleTimer,
  deriveTimerSnapshot,
  getNextPhase,
  pauseTimer,
  phaseDurationMs,
  restoreTimerFromSession,
  resumeTimer,
  startTimer
} from '@core/timer/timerState'
import type { AppSettings, CompletionReason, TimerPhase, TimerSession, TimerSnapshot, TimerState } from '@shared/types'
import type { ClockPort, NotificationPort, SoundPort } from '@main/ports/desktop'
import type {
  AppEventRepository,
  SettingsRepository,
  TaskRepository,
  TimerRuntimeRepository,
  TimerSessionRepository
} from '@main/ports/repositories'
 
export interface TimerServiceDependencies {
  sessions: TimerSessionRepository
  settings: SettingsRepository
  runtime: TimerRuntimeRepository
  events: AppEventRepository
  tasks: Pick<TaskRepository, 'list'>
  clock: ClockPort
  notifier: NotificationPort
  sound: SoundPort
}
 
export interface StartTimerCommand {
  phase?: TimerPhase
  taskId?: string | null
}
 
const isTimerPhase = (value: unknown): value is TimerPhase =>
  value === 'focus' || value === 'shortBreak' || value === 'longBreak'
 
const normalizeTimerState = (state: TimerState): TimerState => {
  const persistedState = state as TimerState & {
    unboundFocusCount?: number
    lastFocusTaskId?: string | null
  }
 
  return {
    ...state,
    unboundFocusCount: persistedState.unboundFocusCount ?? 0,
    lastFocusTaskId: persistedState.lastFocusTaskId ?? null
  }
}
 
export class TimerService {
  private readonly emitter = new EventEmitter()
  private settingsValue: AppSettings | null = null
  private state: TimerState | null = null
 
  constructor(private readonly dependencies: TimerServiceDependencies) {}
 
  async initialize(): Promise<TimerSnapshot> {
    const settings = await this.dependencies.settings.get()
    this.settingsValue = settings
    const now = this.dependencies.clock.now()
    const runtimeState = await this.dependencies.runtime.get()
 
    if (runtimeState) {
      const normalizedRuntimeState = normalizeTimerState(runtimeState)
      const snapshot = deriveTimerSnapshot(normalizedRuntimeState, now)
      this.state = {
        ...normalizedRuntimeState,
        status: snapshot.status,
        remainingMs: snapshot.remainingMs,
        updatedAt: now
      }
 
      if (normalizedRuntimeState.status === 'running') {
        const action = snapshot.status === 'completed' ? 'needs-confirmation' : 'resume'
        await this.dependencies.events.record(
          'timer.restore',
          {
            action,
            sessionId: normalizedRuntimeState.sessionId
          },
          this.dependencies.clock.nowIso()
        )
 
        if (snapshot.status === 'completed' && normalizedRuntimeState.sessionId) {
          await this.dependencies.sessions.finish({
            id: normalizedRuntimeState.sessionId,
            endedAt: this.dependencies.clock.nowIso(),
            actualDurationMs: normalizedRuntimeState.durationMs,
            completed: false,
            completionReason: 'needs-confirmation'
          })
        }
      }
 
      await this.persistState()
      return this.publish()
    }
 
    const activeSession = await this.dependencies.sessions.findActive()
 
    if (!activeSession) {
      this.state = createIdleTimer(settings, now)
      await this.persistState()
      return this.publish()
    }
 
    const restore = restoreTimerFromSession({
      session: activeSession,
      now
    })
    this.state = {
      ...restore.state,
      focusCount: await this.getRestoredFocusCount(activeSession)
    }
 
    await this.dependencies.events.record(
      'timer.restore',
      {
        action: restore.action,
        sessionId: activeSession.id
      },
      this.dependencies.clock.nowIso()
    )
 
    if (restore.action === 'needs-confirmation') {
      await this.dependencies.sessions.finish({
        id: activeSession.id,
        endedAt: this.dependencies.clock.nowIso(),
        actualDurationMs: activeSession.durationMs,
        completed: false,
        completionReason: 'needs-confirmation'
      })
    }
 
    await this.persistState()
    return this.publish()
  }
 
  async start(command: StartTimerCommand = {}): Promise<TimerSnapshot> {
    const settings = await this.requireSettings()
    const requestedPhase = command.phase ?? 'focus'
    if (!isTimerPhase(requestedPhase)) {
      throw new Error(`Invalid timer phase: ${String(requestedPhase)}`)
    }
    const phase = requestedPhase
    const now = this.dependencies.clock.now()
    const taskId = phase === 'focus' ? await this.resolveExplicitFocusTaskId(command.taskId) : null
 
    await this.finishCurrentSession('abandoned')
 
    const session = await this.dependencies.sessions.create({
      phase,
      taskId,
      startedAt: this.dependencies.clock.nowIso(),
      durationMs: phaseDurationMs(phase, settings)
    })
 
    this.state = startTimer(this.requireState(), {
      now,
      phase,
      taskId,
      sessionId: session.id,
      settings
    })
 
    await this.persistState()
    return this.publish()
  }
 
  async pause(): Promise<TimerSnapshot> {
    this.state = pauseTimer(this.requireState(), this.dependencies.clock.now())
    await this.persistState()
    return this.publish()
  }
 
  async bindCurrentTask(taskId: string | null): Promise<TimerSnapshot> {
    const state = this.requireState()
    if (state.status !== 'running' || state.phase !== 'focus' || !state.sessionId) {
      throw new Error('Current timer is not a running focus session')
    }
 
    const resolvedTaskId = await this.resolveExplicitFocusTaskId(taskId)
    const now = this.dependencies.clock.now()
    const nowIso = this.dependencies.clock.nowIso()
 
    await this.dependencies.sessions.updateTask({
      id: state.sessionId,
      taskId: resolvedTaskId,
      updatedAt: nowIso
    })
 
    this.state = {
      ...state,
      taskId: resolvedTaskId,
      unboundFocusCount: 0,
      updatedAt: now
    }
    await this.persistState()
    return this.publish()
  }
 
  async clearDeletedTaskBinding(taskId: string): Promise<void> {
    const state = this.requireState()
    Iif (state.phase !== 'focus' || !state.sessionId) return
    Iif (state.status !== 'running' && state.status !== 'paused') return
    if (state.taskId !== taskId) return
 
    const now = this.dependencies.clock.now()
    const nowIso = this.dependencies.clock.nowIso()
 
    await this.dependencies.sessions.updateTask({
      id: state.sessionId,
      taskId: null,
      updatedAt: nowIso
    })
 
    this.state = {
      ...state,
      taskId: null,
      unboundFocusCount: 0,
      updatedAt: now
    }
    await this.persistState()
    this.publish()
  }
 
  async resume(): Promise<TimerSnapshot> {
    this.state = resumeTimer(this.requireState(), this.dependencies.clock.now())
    await this.persistState()
    return this.publish()
  }
 
  async skip(): Promise<TimerSnapshot> {
    await this.finishCurrentSession('skipped')
    this.state = createIdleTimer(await this.requireSettings(), this.dependencies.clock.now())
    await this.persistState()
    return this.publish()
  }
 
  async reset(): Promise<TimerSnapshot> {
    await this.finishCurrentSession('abandoned')
    this.state = createIdleTimer(await this.requireSettings(), this.dependencies.clock.now())
    await this.persistState()
    return this.publish()
  }
 
  async applySettings(settings: AppSettings): Promise<TimerSnapshot> {
    this.settingsValue = settings
 
    const state = this.requireState()
    Eif (state.status === 'idle') {
      this.state = createIdleTimer(settings, this.dependencies.clock.now())
    }
 
    await this.persistState()
    return this.publish()
  }
 
  async tick(): Promise<TimerSnapshot> {
    const state = this.requireState()
    const snapshot = deriveTimerSnapshot(state, this.dependencies.clock.now())
 
    Iif (state.status !== 'running' || snapshot.status !== 'completed') {
      return this.publish(snapshot)
    }
 
    const completedState = completeTimer(state, this.dependencies.clock.now())
    this.state = completedState
 
    Eif (state.sessionId) {
      await this.dependencies.sessions.finish({
        id: state.sessionId,
        endedAt: this.dependencies.clock.nowIso(),
        actualDurationMs: state.durationMs,
        completed: true,
        completionReason: 'completed'
      })
    }
 
    const completedSnapshot = deriveTimerSnapshot(completedState, this.dependencies.clock.now())
    await this.playDesktopFeedback(completedSnapshot)
 
    const settings = await this.requireSettings()
    const nextPhase = getNextPhase(state.phase, completedState.focusCount, settings)
    const shouldAutoStart = state.phase === 'focus' ? settings.autoStartBreaks : settings.autoStartFocus
 
    if (shouldAutoStart) {
      return this.start({ phase: nextPhase, taskId: nextPhase === 'focus' ? undefined : null })
    }
 
    await this.persistState()
    return this.publish(completedSnapshot)
  }
 
  getSnapshot(): TimerSnapshot {
    return deriveTimerSnapshot(this.requireState(), this.dependencies.clock.now())
  }
 
  onSnapshot(listener: (snapshot: TimerSnapshot) => void): () => void {
    this.emitter.on('snapshot', listener)
    return () => this.emitter.off('snapshot', listener)
  }
 
  private async playDesktopFeedback(snapshot: TimerSnapshot): Promise<void> {
    const settings = await this.requireSettings()
    Eif (settings.notificationsEnabled) {
      await this.dependencies.notifier.showTimerFinished(snapshot)
    }
    Eif (settings.soundEnabled) {
      await this.dependencies.sound.playTimerFinished()
    }
  }
 
  private async resolveExplicitFocusTaskId(taskId: string | null | undefined): Promise<string | null> {
    if (taskId === undefined || taskId === null) {
      return null
    }
 
    const activeTask = (await this.dependencies.tasks.list()).find((task) => task.id === taskId && !task.completedAt)
    if (!activeTask) {
      throw new Error('Selected task must be active')
    }
 
    return taskId
  }
 
  private async requireSettings(): Promise<AppSettings> {
    Iif (!this.settingsValue) {
      this.settingsValue = await this.dependencies.settings.get()
    }
    return this.settingsValue
  }
 
  private async persistState(): Promise<void> {
    try {
      await this.dependencies.runtime.save(this.requireState())
    } catch {
      // Keep the in-memory timer running even when runtime persistence is temporarily unavailable.
    }
  }
 
  private async finishCurrentSession(reason: Exclude<CompletionReason, 'completed' | 'needs-confirmation'>): Promise<void> {
    const state = this.requireState()
    if (!state.sessionId) return
    if (state.status !== 'running' && state.status !== 'paused') return
 
    const snapshot = deriveTimerSnapshot(state, this.dependencies.clock.now())
    await this.dependencies.sessions.finish({
      id: state.sessionId,
      endedAt: this.dependencies.clock.nowIso(),
      actualDurationMs: state.durationMs - snapshot.remainingMs,
      completed: false,
      completionReason: reason
    })
  }
 
  private async getRestoredFocusCount(activeSession: TimerSession): Promise<number> {
    const sessions = await this.dependencies.sessions.list()
    const activeStartedAt = new Date(activeSession.startedAt).getTime()
 
    return sessions.filter((session) => {
      if (session.id === activeSession.id) return false
      if (session.phase !== 'focus' || !session.completed) return false
      return new Date(session.startedAt).getTime() < activeStartedAt
    }).length
  }
 
  private requireState(): TimerState {
    Iif (!this.state) {
      throw new Error('TimerService has not been initialized')
    }
    return this.state
  }
 
  private publish(snapshot = deriveTimerSnapshot(this.requireState(), this.dependencies.clock.now())): TimerSnapshot {
    this.emitter.emit('snapshot', snapshot)
    return snapshot
  }
}