Add an Explain button that has Claude explain a problem
Test and publish the site / publish (push) Successful in 8m15s
Test and publish the site / test (push) Successful in 5m51s

When stuck, the admin can ask Claude for an intuitive explanation of a
problem. It is committed as explain.md and shown as folded sections, so
the reader opens only as much as they need: the key observation, hints
that get stronger, the approach, a walkthrough with an SVG diagram per
step, complexity, pitfalls and a pseudocode sketch.

- internal/claude: streamed call with a JSON-schema reply, high effort,
  the server-side refusal fallback, fixed error messages and logged
  token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5);
  without a key only this feature is off.
- internal/explain: the prompt, the schema, rendering to markdown, and
  a per-problem job tracker. The request starts a job and the page polls,
  since a call outlasts nginx's 120s timeout.
- internal/statement: fetches statements from LeetCode's GraphQL API and
  USACO's problem pages. Others (Codeforces is behind Cloudflare) are
  pasted.
- problem.md holds the statement, editable from the meta editor and
  shown only to the admin. Diagrams are sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-19 20:38:15 +01:00
co-authored by Claude Opus 5.5
parent f0e10d2a58
commit 995b44a57a
27 changed files with 2144 additions and 67 deletions
+219
View File
@@ -0,0 +1,219 @@
package handlers
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/repo"
"adam-french.co.uk/usaco-site/internal/statement"
)
// Fetcher is the part of statement.Fetcher the handlers use, so tests can
// fake the judges.
type Fetcher interface {
Fetch(ctx context.Context, link string) (string, error)
}
func (s *Server) fetcher() Fetcher {
if s.Statements != nil {
return s.Statements
}
return &statement.Fetcher{}
}
// fetchStatement returns the statement behind ?url= (or the saved link) for
// the admin to review in the editor. It saves nothing.
func (s *Server) fetchStatement(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
link := strings.TrimSpace(ctx.Query("url"))
if link == "" {
link = p.URL
}
if u, err := url.Parse(link); link == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "give the problem an http(s) link first"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), 20*time.Second)
defer cancel()
md, err := s.fetcher().Fetch(c, link)
switch {
case errors.Is(err, statement.ErrUnsupported):
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
case err != nil:
log.Printf("[statement] %s: %v", link, err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
default:
ctx.JSON(http.StatusOK, gin.H{"statement": md})
}
}
type explainBody struct {
Note string `json:"note"`
IncludeCode bool `json:"includeCode"`
}
const maxNote = 4 << 10
// Claude can take a few minutes at high effort; this also bounds the
// commit that follows.
const explainTimeout = 10 * time.Minute
// startExplain starts writing explain.md and answers at once; the page polls
// explainStatus. Everything Claude sees is taken from the index now, so a
// sync during the call changes nothing but where the result is committed.
func (s *Server) startExplain(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return
}
var body explainBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
if strings.TrimSpace(p.Statement) == "" && p.URL == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"})
return
}
in := explain.Input{Name: p.Name, Statement: p.Statement, Note: body.Note, Examples: examples(p)}
if body.IncludeCode {
in.Code = mainFile(p)
}
link := p.URL
if !s.jobs.Start(p.Name, func() error { return s.explain(in, link) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "an explanation is already being written"})
return
}
ctx.JSON(http.StatusAccepted, s.jobs.Get(p.Name))
}
func (s *Server) explainStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.jobs.Get(p.Name))
}
}
// explain is one job. Its error is shown to the admin, so every path returns
// a message meant for them and logs the detail.
func (s *Server) explain(in explain.Input, link string) error {
ctx, cancel := context.WithTimeout(context.Background(), explainTimeout)
defer cancel()
// No statement saved: fetch it, and save it alongside the explanation
// so the next one does not need the judge.
fetched := ""
if strings.TrimSpace(in.Statement) == "" {
md, err := s.fetcher().Fetch(ctx, link)
if err != nil {
log.Printf("[explain] %s: fetching %s: %v", in.Name, link, err)
return fmt.Errorf("could not fetch the statement (%v); paste it into the editor", err)
}
in.Statement, fetched = md, md
}
md, err := explain.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[explain] %s: %s: %v", in.Name, f.Msg, f.Err)
return f
}
log.Printf("[explain] %s: %v", in.Name, err)
return errors.New("the explanation could not be written")
}
name := in.Name
err = s.Repo.Mutate(ctx, "Explain "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if fetched != "" {
// Only if it is still missing: the admin may have pasted one
// while Claude was working.
if _, err := os.Stat(filepath.Join(pdir, "problem.md")); os.IsNotExist(err) {
if err := writeOrRemove(filepath.Join(pdir, "problem.md"), fetched); err != nil {
return err
}
}
}
return writeOrRemove(filepath.Join(pdir, "explain.md"), md)
})
var re *requestError
switch {
case err == nil:
return nil
case errors.As(err, &re):
return errors.New(re.msg)
case errors.Is(err, repo.ErrRejected):
return errors.New("the repository changed while saving; try again")
default:
log.Printf("[explain] %s: saving: %v", name, err)
return errors.New("the explanation was written but could not be saved to git")
}
}
// mainFile is the CLI's solution (main.cpp, main.rs...), else the first
// solution file.
func mainFile(p *index.Problem) *index.File {
for i := range p.Files {
if strings.HasPrefix(p.Files[i].Name, "main.") {
return &p.Files[i]
}
}
if len(p.Files) > 0 {
return &p.Files[0]
}
return nil
}
// A case bigger than this is a stress test, not something to trace by hand,
// and a truncated one would mislead.
const maxExample = 2 << 10
// examples are the saved tests that have an expected output, then the
// sample input if no test has the same input. Three is plenty to trace.
func examples(p *index.Problem) []explain.Example {
var out []explain.Example
seen := map[string]bool{}
for _, t := range p.TestSet {
if len(out) == 3 {
return out
}
if t.Output == nil || t.Input.Truncated || len(t.Input.Content) > maxExample || len(t.Output.Content) > maxExample {
continue
}
out = append(out, explain.Example{In: t.Input.Content, Out: t.Output.Content})
seen[strings.TrimSpace(t.Input.Content)] = true
}
if sm := p.Sample; sm != nil && len(out) < 3 && len(sm.Content) <= maxExample && !seen[strings.TrimSpace(sm.Content)] {
out = append(out, explain.Example{In: sm.Content})
}
return out
}