* feat(M13 T-519b): SSE worker_heartbeat + NavBar stand-by badge Aanvulling op scrum4me-mcp PR #25 (worker_heartbeat MCP-tool). - app/api/realtime/solo/route.ts: WorkerHeartbeatPayload type + isWorkerHeartbeatPayload guard + shouldEmit-routing op user_id. - stores/solo-store.ts: workerQuotaPct + workerQuotaCheckAt state + setWorkerQuota action. Reset bij decrementWorkers naar 0. - lib/realtime/use-solo-realtime.ts: handle worker_heartbeat-event, roep setWorkerQuota. - components/solo/nav-status-indicators.tsx: stand-by badge wanneer workerQuotaPct < minQuotaPct + tooltip met drempel. - components/shared/nav-bar.tsx + app/(app)/layout.tsx: minQuotaPct prop plumbing van User.min_quota_pct naar NavStatusIndicators. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(M13 T-520b): pre-flight quota-check sectie in mcp-integration Documenteert de batch-loop-uitbreiding: 1. get_worker_settings → min_quota_pct 2. bin/worker-quota-probe.sh → pct + reset 3. worker_heartbeat naar server (NavBar stand-by-badge) 4. Sleep tot reset bij low quota; anders wait_for_job Verwijst naar bin/worker-quota-probe.sh in scrum4me-docker (zie PR daar). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
197 lines
7 KiB
TypeScript
197 lines
7 KiB
TypeScript
// ST-803 + ST-805 (refactor in ST-806-acceptance): client-side hook die de
|
|
// Solo Paneel realtime stream beheert.
|
|
//
|
|
// - Mount in de (app)-layout via SoloRealtimeBridge zodat hij Server Action-
|
|
// refreshes overleeft (anders kapt Next.js' soft-navigation de SSE).
|
|
// - Opent EventSource('/api/realtime/solo?product_id=...') wanneer
|
|
// productId niet null is; sluit de stream als productId null wordt.
|
|
// - Reconnect met exponential backoff (1s → 30s, reset bij ready).
|
|
// - Pauseert bij document.visibilityState === 'hidden', resumes bij visible.
|
|
// - Cleanup op unmount.
|
|
// - Connection-status (status, showConnectingIndicator) wordt naar de
|
|
// solo-store geschreven; UI-componenten lezen daar uit.
|
|
// - Dispatcht events naar de solo-store via handleRealtimeEvent. Task-
|
|
// updates worden in document.startViewTransition + flushSync gewikkeld
|
|
// zodat het kanban-kaartje soepel naar zijn nieuwe kolom animeert
|
|
// (animatie A — vereist view-transition-name op de cards).
|
|
|
|
'use client'
|
|
|
|
import { useEffect, useRef } from 'react'
|
|
import { flushSync } from 'react-dom'
|
|
import { useSoloStore } from '@/stores/solo-store'
|
|
import type { ClaudeJobEvent, JobState, RealtimeEvent, RealtimeStatus } from '@/stores/solo-store'
|
|
|
|
const BACKOFF_START_MS = 1_000
|
|
const BACKOFF_MAX_MS = 30_000
|
|
const CONNECTING_INDICATOR_DELAY_MS = 4_000
|
|
|
|
export function useSoloRealtime(productId: string | null) {
|
|
const sourceRef = useRef<EventSource | null>(null)
|
|
const backoffRef = useRef<number>(BACKOFF_START_MS)
|
|
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
const indicatorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
|
|
useEffect(() => {
|
|
const setStatus = useSoloStore.getState().setRealtimeStatus
|
|
const handleEvent = useSoloStore.getState().handleRealtimeEvent
|
|
const handleJobEvent = useSoloStore.getState().handleJobEvent
|
|
const initJobs = useSoloStore.getState().initJobs
|
|
const setWorkers = useSoloStore.getState().setWorkers
|
|
const incrementWorkers = useSoloStore.getState().incrementWorkers
|
|
const decrementWorkers = useSoloStore.getState().decrementWorkers
|
|
const setWorkerQuota = useSoloStore.getState().setWorkerQuota
|
|
|
|
if (!productId) {
|
|
// Geen actief product (gebruiker zit niet op /solo) — stream uit
|
|
setStatus('disconnected', false)
|
|
return
|
|
}
|
|
|
|
const close = () => {
|
|
if (sourceRef.current) {
|
|
sourceRef.current.close()
|
|
sourceRef.current = null
|
|
}
|
|
if (reconnectTimerRef.current) {
|
|
clearTimeout(reconnectTimerRef.current)
|
|
reconnectTimerRef.current = null
|
|
}
|
|
}
|
|
|
|
const scheduleIndicator = (next: RealtimeStatus) => {
|
|
if (indicatorTimerRef.current) {
|
|
clearTimeout(indicatorTimerRef.current)
|
|
indicatorTimerRef.current = null
|
|
}
|
|
if (next === 'open') {
|
|
setStatus('open', false)
|
|
} else {
|
|
// Status meteen bijwerken, indicator pas na 4s — voorkomt flikker
|
|
// bij microscopische disconnects.
|
|
setStatus(next, false)
|
|
indicatorTimerRef.current = setTimeout(() => {
|
|
setStatus(useSoloStore.getState().realtimeStatus, true)
|
|
}, CONNECTING_INDICATOR_DELAY_MS)
|
|
}
|
|
}
|
|
|
|
const connect = () => {
|
|
close()
|
|
scheduleIndicator('connecting')
|
|
|
|
const source = new EventSource(
|
|
`/api/realtime/solo?product_id=${encodeURIComponent(productId)}`,
|
|
)
|
|
sourceRef.current = source
|
|
|
|
source.addEventListener('ready', () => {
|
|
backoffRef.current = BACKOFF_START_MS
|
|
scheduleIndicator('open')
|
|
})
|
|
|
|
source.addEventListener('claude_jobs_initial', (e) => {
|
|
if (!e.data) return
|
|
try {
|
|
initJobs(JSON.parse(e.data) as JobState[])
|
|
} catch {
|
|
// ignore malformed payload
|
|
}
|
|
})
|
|
|
|
source.addEventListener('workers_initial', (e) => {
|
|
if (!e.data) return
|
|
try {
|
|
const { count } = JSON.parse(e.data) as { count: number }
|
|
setWorkers(count)
|
|
} catch {
|
|
// ignore malformed payload
|
|
}
|
|
})
|
|
|
|
source.onmessage = (e) => {
|
|
if (!e.data) return
|
|
try {
|
|
const raw = JSON.parse(e.data) as RealtimeEvent | ClaudeJobEvent | { type: string }
|
|
if ('type' in raw) {
|
|
if (raw.type === 'claude_job_enqueued' || raw.type === 'claude_job_status') {
|
|
handleJobEvent(raw as ClaudeJobEvent)
|
|
return
|
|
}
|
|
if (raw.type === 'worker_connected') { incrementWorkers(); return }
|
|
if (raw.type === 'worker_disconnected') { decrementWorkers(); return }
|
|
if (raw.type === 'worker_heartbeat') {
|
|
const hb = raw as {
|
|
type: 'worker_heartbeat'
|
|
last_quota_pct: number
|
|
last_quota_check_at: string
|
|
}
|
|
setWorkerQuota(hb.last_quota_pct, hb.last_quota_check_at)
|
|
return
|
|
}
|
|
return
|
|
}
|
|
const payload = raw as RealtimeEvent
|
|
// Animatie A: kanban-move animeren via View Transitions API. Voor
|
|
// task UPDATE-events wrap'en we de store-update in een view
|
|
// transition. flushSync forceert React om synchroon te renderen
|
|
// tijdens de transition-callback zodat de nieuwe DOM-state wordt
|
|
// gesnapshot voor de animatie.
|
|
const animate =
|
|
payload.entity === 'task' &&
|
|
payload.op === 'U' &&
|
|
typeof document !== 'undefined' &&
|
|
typeof (document as Document & { startViewTransition?: unknown }).startViewTransition ===
|
|
'function'
|
|
if (animate) {
|
|
;(
|
|
document as Document & {
|
|
startViewTransition: (cb: () => void) => unknown
|
|
}
|
|
).startViewTransition(() => {
|
|
flushSync(() => handleEvent(payload))
|
|
})
|
|
} else {
|
|
handleEvent(payload)
|
|
}
|
|
} catch (err) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.error('[realtime] failed to parse event', err, e.data)
|
|
}
|
|
}
|
|
}
|
|
|
|
source.onerror = () => {
|
|
if (sourceRef.current !== source) return
|
|
close()
|
|
scheduleIndicator('disconnected')
|
|
|
|
if (document.visibilityState === 'hidden') return
|
|
const delay = backoffRef.current
|
|
backoffRef.current = Math.min(backoffRef.current * 2, BACKOFF_MAX_MS)
|
|
reconnectTimerRef.current = setTimeout(connect, delay)
|
|
}
|
|
}
|
|
|
|
const onVisibility = () => {
|
|
if (document.visibilityState === 'hidden') {
|
|
close()
|
|
scheduleIndicator('disconnected')
|
|
} else if (sourceRef.current === null) {
|
|
backoffRef.current = BACKOFF_START_MS
|
|
connect()
|
|
}
|
|
}
|
|
|
|
if (document.visibilityState === 'visible') {
|
|
connect()
|
|
}
|
|
document.addEventListener('visibilitychange', onVisibility)
|
|
|
|
return () => {
|
|
document.removeEventListener('visibilitychange', onVisibility)
|
|
if (indicatorTimerRef.current) clearTimeout(indicatorTimerRef.current)
|
|
close()
|
|
}
|
|
}, [productId])
|
|
}
|