fix: resolve 9 MC bugs in HumanFightPage and useHumanChallenge

- BUG-1: Prevent double-tap by locking phase before async submit
- BUG-2: Submit timeout notification to server when timer expires
- BUG-3: Distinct "TIME'S UP!" visual vs "ANSWER SUBMITTED"
- BUG-4: Track consecutive poll failures, show connection lost banner
- BUG-5: Add A-D / 1-4 keyboard shortcuts for MC choices
- BUG-6: Use choice text as v-for key instead of array index
- BUG-7: Deadline-based timer (250ms tick) prevents drift
- BUG-8: Validate choice is in current choices before submit
- BUG-9: Submit empty timeout instead of random choice on expiry

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-03-09 08:39:27 +00:00
co-authored by Claude Opus 4.6
parent 9fdf7a6720
commit c7a1f6cb0b
2 changed files with 121 additions and 46 deletions
+18 -4
View File
@@ -48,10 +48,9 @@ export function useHumanChallenge(
if (humanTimer.value <= 0) {
if (timerHandle) clearInterval(timerHandle)
if (!humanSubmitted.value) {
if (humanChoices.value.length > 0 && !humanAnswer.value.trim()) {
humanAnswer.value = humanChoices.value[Math.floor(Math.random() * humanChoices.value.length)]
}
void submitHumanAnswer()
// BUG-9: Submit empty timeout instead of random choice
humanSubmitted.value = true
void submitTimeout()
}
}
}, 1000)
@@ -76,10 +75,25 @@ export function useHumanChallenge(
}
function submitChoice(choice: string) {
if (humanSubmitted.value) return // Prevent double-tap
humanAnswer.value = choice
humanSubmitted.value = true // Lock immediately before async
void submitHumanAnswer()
}
async function submitTimeout() {
if (!myBotId.value || !humanChallenge.value) return
try {
await fetch(`/api/fights/${fightId.value}/respond/${myBotId.value}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answer: '', timeout: true }),
})
} catch {
// Server will time out on its own
}
}
async function pollForChallenge() {
if (!myBotId.value) return
try {
+103 -42
View File
@@ -11,7 +11,7 @@ const { bot: myBot, isLoggedIn } = useNostr()
const fightId = ref(route.params.fightId as string)
const fight = ref<FightData | null>(null)
const phase = ref<'waiting' | 'challenge' | 'submitted' | 'between' | 'finished' | 'replay' | 'error'>('waiting')
const phase = ref<'waiting' | 'challenge' | 'submitted' | 'timeout' | 'between' | 'finished' | 'replay' | 'error'>('waiting')
const error = ref('')
// Challenge state
@@ -34,6 +34,10 @@ const showTrashTalk = ref(false)
const feedback = ref<'correct' | 'wrong' | null>(null)
const feedbackTimer = ref<ReturnType<typeof setTimeout> | null>(null)
// Polling error tracking (BUG-4 fix)
const consecutivePollErrors = ref(0)
const connectionLost = ref(false)
// Round results tracking
const roundResults = ref<Array<{
round: number
@@ -48,6 +52,7 @@ const opponentName = ref('')
let pollHandle: ReturnType<typeof setInterval> | null = null
let timerHandle: ReturnType<typeof setInterval> | null = null
let timerDeadline = 0 // BUG-7: deadline-based timer
const answerInput = ref<HTMLTextAreaElement | null>(null)
const myBotId = computed(() => myBot.value?.id || '')
@@ -75,14 +80,30 @@ onMounted(() => {
return
}
startPolling()
window.addEventListener('keydown', handleKeyboard)
})
onUnmounted(() => {
stopPolling()
stopTimer()
if (feedbackTimer.value) clearTimeout(feedbackTimer.value)
window.removeEventListener('keydown', handleKeyboard)
})
// BUG-5: Keyboard shortcuts for MC choices (A-D or 1-4)
function handleKeyboard(e: KeyboardEvent) {
if (phase.value !== 'challenge' || !currentChallenge.value?.choices?.length) return
const choices = currentChallenge.value.choices
let idx = -1
const key = e.key.toLowerCase()
if (key >= 'a' && key <= 'd') idx = key.charCodeAt(0) - 97
else if (key >= '1' && key <= '4') idx = parseInt(key) - 1
if (idx >= 0 && idx < choices.length) {
e.preventDefault()
selectChoice(choices[idx])
}
}
function startPolling() {
pollForChallenge()
pollHandle = setInterval(pollForChallenge, 600)
@@ -92,19 +113,28 @@ function stopPolling() {
if (pollHandle) { clearInterval(pollHandle); pollHandle = null }
}
// BUG-7: Deadline-based timer instead of drift-prone setInterval counter
function startTimer(remainingMs: number) {
stopTimer()
remainingSeconds.value = Math.ceil(remainingMs / 1000)
timerDeadline = Date.now() + remainingMs
updateTimerDisplay()
timerHandle = setInterval(() => {
remainingSeconds.value--
updateTimerDisplay()
if (remainingSeconds.value <= 0) {
stopTimer()
if (phase.value === 'challenge') {
phase.value = 'submitted'
// BUG-2: Submit timeout to server so fight can proceed
phase.value = 'timeout'
showFeedback('wrong')
submitTimeout()
}
}
}, 1000)
}, 250) // Check more frequently for precision
}
function updateTimerDisplay() {
const remaining = Math.max(0, timerDeadline - Date.now())
remainingSeconds.value = Math.ceil(remaining / 1000)
}
function stopTimer() {
@@ -117,6 +147,7 @@ function showFeedback(type: 'correct' | 'wrong') {
feedbackTimer.value = setTimeout(() => { feedback.value = null }, 1500)
}
// BUG-4: Track consecutive poll failures, show connection lost
async function pollForChallenge() {
if (!myBotId.value || phase.value === 'finished' || phase.value === 'replay' || phase.value === 'error') return
@@ -125,6 +156,10 @@ async function pollForChallenge() {
if (!res.ok) return
const data = await res.json()
// Reset error tracking on success
consecutivePollErrors.value = 0
connectionLost.value = false
if (data.pending) {
if (phase.value !== 'challenge' || currentChallenge.value?.roundNumber !== data.roundNumber) {
currentChallenge.value = data
@@ -143,25 +178,35 @@ async function pollForChallenge() {
stopTimer()
await loadFight()
phase.value = 'finished'
} else if (phase.value === 'submitted') {
} else if (phase.value === 'submitted' || phase.value === 'timeout') {
phase.value = 'between'
}
} catch {
// Network hiccup, keep polling
consecutivePollErrors.value++
if (consecutivePollErrors.value >= 5) {
connectionLost.value = true
}
}
}
// BUG-1: Prevent double-tap by checking phase before processing
function selectChoice(choice: string) {
if (phase.value !== 'challenge') return
// BUG-8: Validate choice is in current choices
if (!currentChallenge.value?.choices?.includes(choice)) return
answer.value = choice
phase.value = 'submitted' // Immediately lock out further taps
submitAnswer()
}
async function submitAnswer() {
if (!currentChallenge.value || phase.value !== 'challenge') return
if (!currentChallenge.value) return
if (!answer.value.trim()) return
stopTimer()
phase.value = 'submitted'
// Phase already set to 'submitted' in selectChoice for MC,
// but set it here too for text input path
if (phase.value === 'challenge') phase.value = 'submitted'
try {
const res = await fetch(`/api/fights/${fightId.value}/respond/${myBotId.value}`, {
@@ -175,7 +220,6 @@ async function submitAnswer() {
if (res.ok) {
const data = await res.json()
// Show feedback if server tells us if answer was right
if (data.correct !== undefined) {
showFeedback(data.correct ? 'correct' : 'wrong')
}
@@ -188,6 +232,20 @@ async function submitAnswer() {
}
}
// BUG-2: Submit timeout notification to server
async function submitTimeout() {
if (!currentChallenge.value || !myBotId.value) return
try {
await fetch(`/api/fights/${fightId.value}/respond/${myBotId.value}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answer: '', timeout: true }),
})
} catch {
// Server will time out on its own if this fails
}
}
async function loadFight() {
try {
const res = await fetch(`/api/fights/${fightId.value}`)
@@ -244,6 +302,11 @@ function goToArena() {
</div>
</Transition>
<!-- Connection lost banner (BUG-4) -->
<div v-if="connectionLost" class="mb-3 p-2 border-2 border-neon-yellow/30 bg-neon-yellow/5 text-center rounded">
<p class="font-mono text-xs text-neon-yellow">Connection lost reconnecting...</p>
</div>
<!-- PHASE: WAITING -->
<div v-if="phase === 'waiting'" class="flex flex-col items-center justify-center flex-1 gap-4">
<div class="w-12 h-12 border-4 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
@@ -253,7 +316,7 @@ function goToArena() {
<p class="font-mono text-text-muted text-xs">Waiting for first challenge</p>
</div>
<!-- PHASE: CHALLENGE (type your answer) -->
<!-- PHASE: CHALLENGE (pick your answer) -->
<div v-else-if="phase === 'challenge' && currentChallenge" class="slide-up">
<div class="flex items-center justify-between mb-3">
<span class="font-display font-black text-sm tracking-wider text-neon-cyan">
@@ -270,7 +333,7 @@ function goToArena() {
<!-- Timer bar -->
<div class="h-1 bg-white/5 rounded-full mb-3 overflow-hidden">
<div
class="h-full rounded-full transition-all duration-1000 ease-linear"
class="h-full rounded-full transition-all duration-250 ease-linear"
:class="{
'bg-neon-green': remainingSeconds > 10,
'bg-neon-yellow': remainingSeconds > 3 && remainingSeconds <= 10,
@@ -289,21 +352,23 @@ function goToArena() {
{{ currentChallenge.scoring === 'factual' ? 'FACTUAL' : 'CREATIVE' }}
</span>
</div>
<p class="font-mono text-sm text-text-primary leading-relaxed">
<p class="font-mono text-sm text-text-primary leading-relaxed whitespace-pre-wrap break-words">
{{ currentChallenge.prompt }}
</p>
</div>
<!-- Multiple choice buttons (always shown all challenges now have choices) -->
<!-- Multiple choice buttons -->
<!-- BUG-6: Use choice text as key instead of array index -->
<!-- BUG-5: Keyboard hints shown via A/B/C/D labels -->
<div v-if="currentChallenge?.choices?.length" class="space-y-2 mb-3">
<button
v-for="(choice, i) in currentChallenge.choices"
:key="i"
:key="`${currentChallenge.roundNumber}-${choice}`"
class="w-full min-h-[48px] px-4 py-3 text-left text-sm font-mono
border-2 border-border bg-surface/50 rounded
hover:border-neon-cyan/50 hover:bg-neon-cyan/5
active:bg-neon-cyan/10 active:border-neon-cyan
transition-all"
active:scale-[0.97] active:bg-neon-cyan/10 active:border-neon-cyan
transition-all break-words"
@click="selectChoice(choice)"
>
<span class="text-neon-cyan/50 font-display font-bold mr-2">{{ String.fromCharCode(65 + i) }}.</span>
@@ -311,37 +376,33 @@ function goToArena() {
</button>
</div>
<!-- Free text input hidden for now, all challenges use multiple choice.
Kept for future reintroduction of creative open-ended input. -->
<!--
<template v-if="!hasChoices">
<textarea ref="answerInput" v-model="answer" rows="4" placeholder="Type your answer..."
class="w-full bg-surface border-2 border-border px-4 py-3 text-sm font-mono
text-text-primary placeholder-text-muted resize-none rounded
focus:outline-none focus:border-neon-pink/50 transition-colors mb-2"
@keydown.ctrl.enter="submitAnswer" @keydown.meta.enter="submitAnswer" />
<button v-if="!showTrashTalk" class="font-mono text-[10px] text-text-muted hover:text-neon-yellow transition-colors mb-2"
@click="showTrashTalk = true">+ add trash talk</button>
<input v-if="showTrashTalk" v-model="trashTalk" type="text" maxlength="200" placeholder="Talk smack..."
class="w-full bg-surface border border-border px-3 py-2 text-xs font-mono
text-neon-yellow placeholder-text-muted rounded focus:outline-none focus:border-neon-yellow/50 transition-colors mb-2" />
<button class="w-full min-h-[48px] py-4 bg-neon-pink/10 border-2 border-neon-pink text-neon-pink
font-display font-black text-lg tracking-[0.15em] rounded hover:bg-neon-pink/20 transition-all neon-border-pink
disabled:opacity-30 disabled:cursor-not-allowed" :disabled="!answer.trim()" @click="submitAnswer">SUBMIT ANSWER</button>
<p class="font-mono text-[10px] text-text-muted text-center mt-1">Ctrl+Enter to submit</p>
</template>
-->
<!-- Keyboard hint -->
<p v-if="currentChallenge?.choices?.length" class="font-mono text-[9px] text-text-muted text-center">
Press A-D or 1-4 to select
</p>
</div>
<!-- PHASE: SUBMITTED / BETWEEN ROUNDS -->
<div v-else-if="phase === 'submitted' || phase === 'between'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
<!-- PHASE: SUBMITTED (BUG-3: distinguish from timeout) -->
<div v-else-if="phase === 'submitted'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
<div class="w-10 h-10 border-3 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
<p class="font-display text-neon-cyan text-sm tracking-widest">
{{ phase === 'submitted' ? 'ANSWER SUBMITTED' : 'NEXT ROUND...' }}
</p>
<p class="font-display text-neon-cyan text-sm tracking-widest">ANSWER SUBMITTED</p>
<p class="font-mono text-text-muted text-xs">Waiting for round result</p>
</div>
<!-- PHASE: TIMEOUT (BUG-3: distinct visual for timer expiry) -->
<div v-else-if="phase === 'timeout'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
<div class="w-10 h-10 border-3 border-ko/30 border-t-ko rounded-full animate-spin" />
<p class="font-display text-ko text-lg tracking-widest">TIME'S UP!</p>
<p class="font-mono text-text-muted text-xs">Waiting for round result</p>
</div>
<!-- PHASE: BETWEEN ROUNDS -->
<div v-else-if="phase === 'between'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
<div class="w-10 h-10 border-3 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
<p class="font-display text-neon-cyan text-sm tracking-widest">NEXT ROUND...</p>
<p class="font-mono text-text-muted text-xs">Preparing challenge</p>
</div>
<!-- PHASE: FINISHED -->
<div v-else-if="phase === 'finished' && fight" class="slide-up">
<div class="text-center mb-6">