Skip to content

Commit d83d228

Browse files
Final implementation with improved error handling and formatting
Co-authored-by: kevinjosethomas <46242684+kevinjosethomas@users.noreply.github.com>
1 parent 749bd7c commit d83d228

File tree

4 files changed

+47
-19
lines changed

4 files changed

+47
-19
lines changed

src/api/analysis/analysis.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -683,13 +683,16 @@ export const storeEngineAnalysis = async (
683683
gameId: string,
684684
analysisData: EngineAnalysisData,
685685
): Promise<void> => {
686-
const res = await fetch(buildUrl(`analysis/store_engine_analysis/${gameId}`), {
687-
method: 'POST',
688-
headers: {
689-
'Content-Type': 'application/json',
686+
const res = await fetch(
687+
buildUrl(`analysis/store_engine_analysis/${gameId}`),
688+
{
689+
method: 'POST',
690+
headers: {
691+
'Content-Type': 'application/json',
692+
},
693+
body: JSON.stringify(analysisData),
690694
},
691-
body: JSON.stringify(analysisData),
692-
})
695+
)
693696

694697
if (res.status === 401) {
695698
throw new Error('Unauthorized')

src/hooks/useAnalysisController/useAnalysisController.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ import { useMoveRecommendations } from './useMoveRecommendations'
1919
import { MaiaEngineContext } from 'src/contexts/MaiaEngineContext'
2020
import { generateColorSanMapping, calculateBlunderMeter } from './utils'
2121
import { StockfishEngineContext } from 'src/contexts/StockfishEngineContext'
22-
import {
23-
collectEngineAnalysisData,
24-
generateAnalysisCacheKey
22+
import {
23+
collectEngineAnalysisData,
24+
generateAnalysisCacheKey,
2525
} from 'src/lib/analysisStorage'
2626
import { storeEngineAnalysis } from 'src/api/analysis/analysis'
2727

@@ -92,12 +92,21 @@ export const useAnalysisController = (
9292

9393
try {
9494
const analysisData = collectEngineAnalysisData(game.tree)
95-
95+
9696
// Only save if there's actually some analysis to save
9797
if (analysisData.positions.length === 0) {
9898
return
9999
}
100100

101+
// Check if we have meaningful analysis (decent depth or Maia data)
102+
const hasMeaningfulAnalysis = analysisData.positions.some(
103+
(pos) => (pos.stockfish && pos.stockfish.depth >= 12) || pos.maia,
104+
)
105+
106+
if (!hasMeaningfulAnalysis) {
107+
return
108+
}
109+
101110
// Generate a cache key to avoid unnecessary saves
102111
const cacheKey = generateAnalysisCacheKey(analysisData)
103112
if (cacheKey === lastSavedCacheKey) {
@@ -106,7 +115,11 @@ export const useAnalysisController = (
106115

107116
await storeEngineAnalysis(game.id, analysisData)
108117
setLastSavedCacheKey(cacheKey)
109-
console.log('Analysis saved to backend:', analysisData.positions.length, 'positions')
118+
console.log(
119+
'Analysis saved to backend:',
120+
analysisData.positions.length,
121+
'positions',
122+
)
110123
} catch (error) {
111124
console.warn('Failed to save analysis to backend:', error)
112125
// Don't show error to user as this is background functionality
@@ -123,11 +136,13 @@ export const useAnalysisController = (
123136
// Set up new timer to save every 10 seconds
124137
autoSaveTimerRef.current = setInterval(saveAnalysisToBackend, 10000)
125138

126-
// Cleanup on unmount
139+
// Cleanup on unmount or game change - save one last time
127140
return () => {
128141
if (autoSaveTimerRef.current) {
129142
clearInterval(autoSaveTimerRef.current)
130143
}
144+
// Final save when component unmounts or game changes
145+
saveAnalysisToBackend()
131146
}
132147
}, [saveAnalysisToBackend])
133148

@@ -418,6 +433,7 @@ export const useAnalysisController = (
418433
cancelAnalysis: cancelGameAnalysis,
419434
resetProgress: resetGameAnalysisProgress,
420435
isEnginesReady: stockfish.isReady() && maia.status === 'ready',
436+
saveAnalysis: saveAnalysisToBackend,
421437
},
422438
}
423439
}

src/lib/analysisStorage.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@ export const applyEngineAnalysisData = (
7373
sent: true,
7474
depth: stockfish.depth,
7575
model_move: Object.keys(stockfish.cp_vec)[0] || '',
76-
model_optimal_cp: Math.max(...Object.values(stockfish.cp_vec).map(Number), 0),
76+
model_optimal_cp: Math.max(
77+
...Object.values(stockfish.cp_vec).map(Number),
78+
0,
79+
),
7780
cp_vec: stockfish.cp_vec,
7881
cp_relative_vec: calculateRelativeCp(stockfish.cp_vec),
7982
}
@@ -110,16 +113,18 @@ const calculateRelativeCp = (cpVec: {
110113
/**
111114
* Generate a unique cache key for analysis data
112115
*/
113-
export const generateAnalysisCacheKey = (analysisData: EngineAnalysisData): string => {
116+
export const generateAnalysisCacheKey = (
117+
analysisData: EngineAnalysisData,
118+
): string => {
114119
// Create a hash-like key based on positions and their analysis
115-
const keyData = analysisData.positions.map(pos => ({
120+
const keyData = analysisData.positions.map((pos) => ({
116121
ply: pos.ply,
117122
fen: pos.fen,
118123
hasStockfish: !!pos.stockfish,
119124
stockfishDepth: pos.stockfish?.depth || 0,
120125
hasMaia: !!pos.maia,
121-
maiaModels: pos.maia ? Object.keys(pos.maia).sort() : []
126+
maiaModels: pos.maia ? Object.keys(pos.maia).sort() : [],
122127
}))
123-
128+
124129
return JSON.stringify(keyData)
125-
}
130+
}

src/pages/analysis/[...id].tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,11 @@ const AnalysisPage: NextPage = () => {
8888
const storedAnalysis = await getEngineAnalysis(game.id)
8989
if (storedAnalysis && storedAnalysis.positions.length > 0) {
9090
applyEngineAnalysisData(game.tree, storedAnalysis)
91-
console.log('Loaded stored analysis:', storedAnalysis.positions.length, 'positions')
91+
console.log(
92+
'Loaded stored analysis:',
93+
storedAnalysis.positions.length,
94+
'positions',
95+
)
9296
}
9397
} catch (error) {
9498
console.warn('Failed to load stored analysis:', error)

0 commit comments

Comments
 (0)