import { useEffect, useMemo, useRef, useState } from 'react' import type { AutoReservationState, ClockCalibrationSettings, ClockEstimate, ReservationRequest, ReservationResult, TimingTestResult, } from '../type/reservation' import { CLOCK_CALIBRATION_DEFAULTS } from '../type/reservation' const KST_OFFSET_MS = 9 * 60 * 60 * 1_000 const CLOCK_SETTINGS_STORAGE_KEY = 'escape-reserve.clock-calibration.v1' const LEGACY_CLOCK_SETTINGS_STORAGE_KEY = 'reserve-escape.clock-calibration.v1' function loadClockSettings(): ClockCalibrationSettings { try { const saved = window.localStorage.getItem(CLOCK_SETTINGS_STORAGE_KEY) ?? window.localStorage.getItem(LEGACY_CLOCK_SETTINGS_STORAGE_KEY) return saved ? { ...CLOCK_CALIBRATION_DEFAULTS, ...JSON.parse(saved) } : { ...CLOCK_CALIBRATION_DEFAULTS } } catch { return { ...CLOCK_CALIBRATION_DEFAULTS } } } interface AutomationPanelProps { request: ReservationRequest | null captchaToken: string captchaPastedAtMs: number | null onTokenConsumed: () => void onResult: (result: ReservationResult) => void } function toKstInput(epochMs: number) { const value = new Date(epochMs + KST_OFFSET_MS) return `${value.getUTCFullYear()}-${String(value.getUTCMonth() + 1).padStart(2, '0')}-${String(value.getUTCDate()).padStart(2, '0')}T${String(value.getUTCHours()).padStart(2, '0')}:${String(value.getUTCMinutes()).padStart(2, '0')}:${String(value.getUTCSeconds()).padStart(2, '0')}.${String(value.getUTCMilliseconds()).padStart(3, '0')}` } function parseKstInput(value: string) { const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/) if (!match) return Number.NaN return Date.UTC( Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]) - 9, Number(match[5]), Number(match[6] ?? 0), Number((match[7] ?? '0').padEnd(3, '0')), ) } function formatClock(epochMs: number) { return new Intl.DateTimeFormat('ko-KR', { timeZone: 'Asia/Seoul', hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', fractionalSecondDigits: 3, }).format(epochMs) } function formatDuration(milliseconds: number) { const sign = milliseconds < 0 ? '-' : '' const absolute = Math.abs(milliseconds) if (absolute < 1_000) return `${sign}${absolute.toFixed(0)}ms` const seconds = absolute / 1_000 if (seconds < 60) return `${sign}${seconds.toFixed(3)}초` return `${sign}${Math.floor(seconds / 60)}분 ${(seconds % 60).toFixed(1)}초` } function Metric({ label, value, tone = 'normal' }: { label: string; value: string; tone?: 'normal' | 'good' | 'warn' }) { return (

{label}

{value}

) } function SampleGraph({ estimate }: { estimate: ClockEstimate }) { const accepted = estimate.samples.filter((sample) => sample.accepted).slice(-60) if (accepted.length < 2) return
표본을 수집하는 중입니다.
const width = 600 const height = 112 const maxRtt = Math.max(1, ...accepted.map((sample) => sample.rttMs)) const maxOffsetDelta = Math.max(50, ...accepted.map((sample) => Math.abs(sample.offsetEstimateMs - estimate.offsetMs))) const points = accepted.map((sample, index) => { const x = accepted.length === 1 ? 0 : index * width / (accepted.length - 1) const y = height / 2 - ((sample.offsetEstimateMs - estimate.offsetMs) / maxOffsetDelta) * (height * 0.38) return `${x.toFixed(1)},${y.toFixed(1)}` }).join(' ') return (
{accepted.map((sample, index) => { const barWidth = Math.max(2, width / accepted.length - 2) const barHeight = sample.rttMs / maxRtt * height * 0.35 return })}
보라 선: 오프셋 편차청록 막대: RTT
) } export default function AutomationPanel({ request, captchaToken, captchaPastedAtMs, onTokenConsumed, onResult, }: AutomationPanelProps) { const [clock, setClock] = useState(null) const [autoState, setAutoState] = useState({ status: 'idle', tokenStatus: 'empty' }) const [nowMs, setNowMs] = useState(Date.now()) const [targetInput, setTargetInput] = useState(() => toKstInput(Date.now() + 30_000)) const [userOffsetMs, setUserOffsetMs] = useState(0) const [busy, setBusy] = useState<'monitor' | 'test' | 'arm' | null>(null) const [error, setError] = useState('') const [timingTest, setTimingTest] = useState(null) const [settingsOpen, setSettingsOpen] = useState(false) const [clockSettings, setClockSettings] = useState(loadClockSettings) const previousFingerprint = useRef('') const previousAutoStatus = useRef(autoState.status) const previousCaptchaAt = useRef(null) const targetServerTimeMs = parseKstInput(targetInput) const liveServerTimeMs = clock ? clock.estimatedServerTimeMs + (nowMs - clock.observedAtMs) : nowMs const countdownMs = Number.isFinite(targetServerTimeMs) ? targetServerTimeMs - liveServerTimeMs : 0 const tokenAgeMs = captchaPastedAtMs ? nowMs - captchaPastedAtMs : Number.POSITIVE_INFINITY const tokenAgeAtTargetMs = captchaPastedAtMs && Number.isFinite(targetServerTimeMs) ? targetServerTimeMs - (captchaPastedAtMs + (clock?.offsetMs ?? 0)) : Number.POSITIVE_INFINITY const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000 const armed = autoState.status === 'armed' || autoState.status === 'firing' const requestFingerprint = useMemo(() => request ? JSON.stringify({ ...request, captchaToken: request.captchaToken ? `${request.captchaToken.length}:${request.captchaToken.slice(-8)}` : '', }) : '', [request]) useEffect(() => { const unsubscribeClock = window.reservationApi.subscribeClock(setClock) const unsubscribeAuto = window.reservationApi.subscribeAutoState(setAutoState) void Promise.all([ window.reservationApi.configureClock(clockSettings).then((estimate) => { setClock(estimate) setClockSettings(estimate.calibrationSettings) }), window.reservationApi.getAutoReservationState().then(setAutoState), ]).catch(() => undefined) const interval = window.setInterval(() => setNowMs(Date.now()), 50) return () => { unsubscribeClock() unsubscribeAuto() window.clearInterval(interval) } }, []) useEffect(() => { if (previousFingerprint.current && previousFingerprint.current !== requestFingerprint && autoState.status === 'armed') { void window.reservationApi.disarmAutoReservation().then(setAutoState) } previousFingerprint.current = requestFingerprint }, [requestFingerprint, autoState.status]) useEffect(() => { if (!captchaPastedAtMs || captchaPastedAtMs === previousCaptchaAt.current || armed) return previousCaptchaAt.current = captchaPastedAtMs const estimatedServerNow = clock ? clock.estimatedServerTimeMs + (Date.now() - clock.observedAtMs) : Date.now() if (!Number.isFinite(targetServerTimeMs) || targetServerTimeMs <= estimatedServerNow + 150) { setTargetInput(toKstInput(estimatedServerNow + 30_000)) } }, [armed, captchaPastedAtMs, clock, targetServerTimeMs]) useEffect(() => { if (previousAutoStatus.current !== autoState.status) { if (autoState.status === 'firing') onTokenConsumed() if ((autoState.status === 'succeeded' || autoState.status === 'failed') && autoState.result) onResult(autoState.result) previousAutoStatus.current = autoState.status } }, [autoState, onResult, onTokenConsumed]) const toggleMonitor = async () => { setBusy('monitor') setError('') try { setClock(clock?.monitoring ? await window.reservationApi.stopClockMonitor() : await window.reservationApi.startClockMonitor()) } catch (reason) { setError(reason instanceof Error ? reason.message : '서버시간 모니터를 전환하지 못했습니다.') } finally { setBusy(null) } } const runTimingTest = async () => { setBusy('test') setError('') setTimingTest(null) try { const current = clock ? clock.estimatedServerTimeMs + (Date.now() - clock.observedAtMs) : Date.now() setTimingTest(await window.reservationApi.runTimingTest({ targetServerTimeMs: current + 3_000, userOffsetMs, })) } catch (reason) { setError(reason instanceof Error ? reason.message : '시간 테스트에 실패했습니다.') } finally { setBusy(null) } } const saveClockSettings = async () => { setBusy('monitor') setError('') try { const estimate = await window.reservationApi.configureClock(clockSettings) setClock(estimate) setClockSettings(estimate.calibrationSettings) window.localStorage.setItem(CLOCK_SETTINGS_STORAGE_KEY, JSON.stringify(estimate.calibrationSettings)) setSettingsOpen(false) } catch (reason) { setError(reason instanceof Error ? reason.message : '시간 보정 설정을 저장하지 못했습니다.') } finally { setBusy(null) } } const arm = async () => { setError('') if (!request) return setError('예약 정보, 인원, 예약자 정보와 동의를 모두 완료해주세요.') if (!captchaPastedAtMs || !tokenReady) return setError('목표 시각에 90초 이내인 유효한 캡차 토큰이 필요합니다.') if (!Number.isFinite(targetServerTimeMs)) return setError('실행 시각을 올바르게 입력해주세요.') setBusy('arm') try { if (!clock?.monitoring) setClock(await window.reservationApi.startClockMonitor()) setAutoState(await window.reservationApi.armAutoReservation({ request, targetServerTimeMs, userOffsetMs, captchaPastedAtMs, })) } catch (reason) { setError(reason instanceof Error ? reason.message : '자동 예약을 시작하지 못했습니다.') } finally { setBusy(null) } } const disarm = async () => { setError('') try { setAutoState(await window.reservationApi.disarmAutoReservation()) onTokenConsumed() } catch (reason) { setError(reason instanceof Error ? reason.message : '자동 예약을 해제하지 못했습니다.') } } const qualityTone = clock?.quality === 'good' ? 'good' : clock?.quality === 'poor' || clock?.quality === 'unavailable' ? 'warn' : 'normal' return (

Precision clock

관측 서버시간

HTTP Date는 초 단위이며 아래 값은 RTT 보정 추정치와 신뢰구간입니다.

{formatClock(liveServerTimeMs)}

= 0 ? '+' : ''}${(clock?.recommendedCorrectionMs ?? 0).toFixed(1)}ms`} />
{clock?.warning &&

{clock.warning} 품질이 낮아도 마지막 유효 추정값으로 1회 실행합니다.

}
{settingsOpen &&
{([ ['scanWindowMs', '경계 탐색 범위 (ms)', 100, 450], ['probeIntervalMs', '경계 측정 간격 (ms)', 25, 200], ['initialBoundarySpacingSec', '초기 경계 간격 (초)', 1, 10], ['requiredBoundaryCount', '최소 경계 수', 3, 12], ['historySize', '경계 기록 수', 3, 30], ['maxBoundarySpreadMs', '최대 경계 편차 (ms)', 30, 500], ['maxProbeRttMs', '최대 허용 RTT (ms)', 100, 1500], ['maintenanceIntervalSec', '안정화 후 재검증 (초)', 5, 120], ['sampleWindowSize', '표본 보관 수', 60, 600], ] as const).map(([key, label, min, max]) => )}

최소 경계 수와 편차 조건을 모두 통과한 경우에만 추천 보정을 자동 적용합니다. 설정은 앱 메모리에만 유지됩니다.

}

시간 테스트

3초 뒤 HEAD 요청으로 스케줄러와 도착 오차를 측정합니다.

{timingTest &&
= 0 ? '+' : ''}${timingTest.arrivalErrorMs.toFixed(1)}ms`} tone={Math.abs(timingTest.arrivalErrorMs) <= timingTest.uncertaintyMs ? 'good' : 'warn'} />= 0 ? '+' : ''}${timingTest.schedulerJitterMs.toFixed(1)}ms`} />
}

단일 요청 자동 예약

목표 서버 도착 시각에 토큰 1개를 소비해 정확히 한 번 제출합니다.

{autoState.status}
0 ? 'good' : 'warn'} />
토큰{captchaToken ? `${captchaToken.slice(0, 6)}••••${captchaToken.slice(-4)} · ${formatDuration(tokenAgeMs)}` : '입력되지 않음'}
{autoState.snapshot && <>
고정 스냅샷{autoState.snapshot.themeName} · {autoState.snapshot.date} {autoState.snapshot.timeLabel} · {autoState.snapshot.person}명
예정 발송{autoState.timeline?.plannedSendAtMs ? formatClock(autoState.timeline.plannedSendAtMs) : '계산 중'}
}
{autoState.timeline?.actualSendAtMs &&
= 0 ? '+' : ''}${autoState.timeline.arrivalErrorMs.toFixed(1)}ms`} />
} {(error || autoState.message) &&

{error || autoState.message}

} {!armed && (!request || !tokenReady) &&

{!request ? '예약자 정보·인원·동의와 CAPTCHA 인증을 완료해주세요.' : tokenAgeAtTargetMs < 0 ? '실행 시각이 이미 지났습니다. 미래 시각으로 변경해주세요.' : 'CAPTCHA 인증 후 90초 이내의 실행 시각을 입력해주세요.'}

}
{armed ? : }
) }